简体   繁体   中英

Adding numbers in GUI giving unexpected result?

The following is a simple code that takes in two numbers and adds them in a gui. For some reason the output is not the sum of the two numbers, but is instead a random number. Please tell me what is going on. Here is my code:

import javax.swing.JOptionPane;


public class GUI {

    public static void main(String[] args) {

        String fn = JOptionPane.showInputDialog("Enter first number");
        String sn = JOptionPane.showInputDialog("Enter second number");

        int num1 = Integer.parseInt(fn); //Converts a string into an integer, since showInputDialog can only take in a string
        int num2 = Integer.parseInt(fn);

        int sum = num1 + num2;

        JOptionPane.showMessageDialog(null, "The answer is "+sum, "This is the title", JOptionPane.PLAIN_MESSAGE);

    }

}

For example, if I enter the first and second numbers as 5 and 6 respectively, instead of an outcome of 11 I get an outcome of 10. Any help would be appreciated.

It shouldn't be a random number, it should be double the first number because num2 is also fn

int num2 = Integer.parseInt(fn);

This is likely a typo and should be:

int num2 = Integer.parseInt(sn);

Things like this are why you should name variables properly. ie. firstNumber and secondNumber it improves readability vastly and will likely result in it being easier to spot typos like this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM