在Java,NetBeans中,我正在尝试制作一个按下按钮时自动添加的计算器。因此,例如,当您点击1时,计算器上的先前金额将加1。如果您达到2,则先前的金额将增加2.等等。
int a = 3;
然而在display.setText(a + display);它出现了错误,它们必须是字符串,所以如何将2个字符串加在一起?
理论上它应为3,因为显示为= 0。
我如何显示两个数字的值?
答案 0 :(得分:2)
您需要将Strings
投射到Integers
才能执行数学运算。要显示结果,您需要将Integer结果转换回String。例如
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;
}
答案 1 :(得分:0)
如果display
是Swing GUI组件,例如JLabel,则不能在算术表达式中使用它。您无法添加或减少标签或文本字段。您必须执行以下步骤:
你可以这样试试:
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));