2

Java、NetBeans で、ボタンを押すと自動的に加算される電卓を作ろうとしています。たとえば、1 をヒットすると、電卓の前の金額が 1 加算されます。2 をヒットすると、前の金額が 2 加算されます。

int a = 3;

ただし、display.setText(a + ディスプレイ); 文字列でなければならないというエラーが表示されるので、2 つの文字列を一緒に追加するにはどうすればよいですか?

表示が=~0なので理論的には3になるはずです。

両方の数値の値を表示するにはどうすればよいですか?

4

2 に答える 2

2

計算を実行するには、にキャストStringsする必要があります。Integers結果を表示するには、整数の結果を文字列に変換する必要があります。例えば

String a = "42";
String b = "6";

int addition = Integer.parseInt(a) + Integer.parseInt(b);
display.setText(Integer.toString(addition));

これが電卓であり、数値しか入力できないことがわかっている場合、これらの任意の文字列を数値に変換しても問題ありません。ただし、一般にInteger.parseInt()、入力が数値でない場合は失敗する可能性があることに注意してください。

更新: 整数計算機を実装するための基本的な青写真

int currentValue = 0; //at the beginning, the user has not typed anything

//here, I am assuming you have a method that listens for all the button presses, then you could
//call a method like this depending on which button was pressed
public void buttonPressed(String value) {
    currentValue += Integer.parseInt(value);
    calculatorLabelDisplay.setText(Integer.toString(currentValue));
}

//here, I am assuming there is some button listener for the "clear" button
public void clearButtonPressed() {
    currentValue = 0;
}
于 2013-03-30T19:00:13.443 に答える
0

が JLabel などの Swing GUI コンポーネントである場合display、算術式では使用できません。ラベルまたはテキストフィールドを追加または削除することはできません。次の手順を実行する必要があります。

  1. テキスト入力を文字列として読み取ります
  2. 文字列を整数などの数値変数に変換します
  3. 手順 (2) で作成した整数を使用して項を計算します。

次のように試すことができます。

String textFieldInput = display.getText();

int sum = 10;   // This might become a private attribute of your object instead of a local var?

int newNumber = 0;
try {
    newNumber = Integer.parseInt(textFieldInput);
} catch (Exception ex) {
    // Watch out: Parsing the number string can fail because the user can input anything, like for example, "lol!", which isn't a number
    System.out.println("Error while trying to parse the number input. Did you enter your name or something?!");
}

sum += newNumber;

System.out.println ("New sum = " + sum);
display.setText(Integer.toString(sum));
于 2013-03-30T19:04:39.627 に答える