2

In Java, NetBeans, I'm trying to make a calculator that adds automatically when you press a button. So for example when you hit 1 the previous amount on the calculator is added by 1. If you hit 2 the previous amount is added by 2. etc.

int a = 3;

However on the display.setText(a + display); it comes up with the error that they have to be strings, so how do I add 2 strings together?

In theory it should be 3 as display is = to 0.

How would I display the value of both the numbers?

4

2 回答 2

2

You'll need to cast Strings to Integers to perform math. To display the result, you'll want to convert the Integer result back to a String. For example

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

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

Given that this is a calculator and you know that they can only type numbers, then you should be fine converting these arbitrary Strings to numbers. But, note that in general, Integer.parseInt() may fail if the input is not a number.

UPDATE: basic blueprint for implementing integer calculator

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

If display is a Swing GUI component, for example a JLabel, you cannot use it in arithmetic expressions. You can't add or substract labels or textfields. You have to do these steps:

  1. Read the text input as a String
  2. Convert the String into a numeric variable, e.g. Integer
  3. Calculate your term using the Integer created in step (2)

You can try it like this:

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 回答