我的大部分代码都是工作代码,就在我尝试添加用户输入的乘法时,我开始出错了。你能给我建议如何做得更好或摆脱错误吗?
package resittests;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Inputting {
public static void main(String[] args) {
Scanner Scan = new Scanner (System.in); // Creates the Scanner to allow input
System.out.print("Enter a Number");
String input = null;
String first = Scan.next();
int num1 = Integer.parseInt(input);
String Second; // Second Declared as a string
Second = JOptionPane.showInputDialog("Enter Another Number");
String input2 = null;
int num2 = Integer.parseInt(input2);
System.out.print("What is your Name?");
String name = Scan.next();
String Age; // Age Declared as a String
Age = JOptionPane.showInputDialog("Enter your age ");
System.out.print( name + " "+ "(Aged" + " " + Age + ")" + "," + "your answer is " + (num1 * num2) );
}
}
答案 0 :(得分:0)
线程中的异常" main" java.lang.NumberFormatException:java.lang.Integer.parseInt(Integer.java:542)中的null
如果Integer.parseInt
无法将参数String
解析为int
,则抛出NumberFormatException - 堆栈跟踪指示它尝试解析的值,在本例中为{{ 1}}。原因是:您传递给null
的字符串是Integer.parseInt
。如果要解析用户输入,则将用户输入String传递给null
,例如:
Integer.parseInt
请注意,如果用户未输入有效整数//String input = null;
String first = Scan.next();
//int num1 = Integer.parseInt(input);
int num1 = Integer.parseInt(first);
,则会抛出Integer.parseInt