Search code examples
javastringnetbeansintsettext

How to make a Calculator that add automaticly


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?


Solution

  • 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;
    }