計算を実行するには、にキャスト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;
}