简体   繁体   English

在GUI中添加数字会产生意外结果?

[英]Adding numbers in GUI giving unexpected result?

The following is a simple code that takes in two numbers and adds them in a gui. 以下是一个简单的代码,它接受两个数字并将它们添加到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. 例如,如果我分别输入第一个数字和第二个数字分别为5和6,而不是11,则得到10。任何帮助将不胜感激。

It shouldn't be a random number, it should be double the first number because num2 is also fn 它不应该是随机数,它应该是第一个数字的两倍,因为num2也是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. firstNumbersecondNumber极大地提高了可读性,并可能导致更容易发现这样的错字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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