[英]Adding numbers read from a file to a totalAmount initialized to 0 giving an unexpected result
[英]Adding numbers in GUI giving unexpected result?
以下是一個簡單的代碼,它接受兩個數字並將它們添加到gui中。 由於某種原因,輸出不是兩個數字的和,而是一個隨機數。 請告訴我發生了什么事。 這是我的代碼:
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);
}
}
例如,如果我分別輸入第一個數字和第二個數字分別為5和6,而不是11,則得到10。任何幫助將不勝感激。
它不應該是隨機數,它應該是第一個數字的兩倍,因為num2也是fn
int num2 = Integer.parseInt(fn);
這可能是拼寫錯誤,應為:
int num2 = Integer.parseInt(sn);
這樣的事情就是為什么您應該正確命名變量的原因。 即。 firstNumber
和secondNumber
極大地提高了可讀性,並可能導致更容易發現這樣的錯字。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.