所以我将Java作为数学学位要求的一部分,并且偶然发现了这段代码的问题。本质上,代码应该从用户那里获取数字,直到他们输入零。只要输入数字,它就可以正常工作。但是,如果用户输入字母或符号,程序将获得异常。有没有一种简单的方法可以将用户输入验证为数字而不会出现异常?
import java.util.Scanner;
public class SamsAdder
{
public static void main(String[] args)
{
double userInput = 1;
double sum = 0;
Scanner in = new Scanner (System.in);
while(userInput != 0)
{
System.out.println("Enter a number. (0 to quit):");
userInput = in.nextDouble();
sum = sum + userInput;
}
System.out.println("The sum of the numbers is " + sum + ".");
}
}
所以我在你展示的时候尝试过try / catch。我仍然会得到非数字的例外。输入代码如下:
while(userInput != 0)
{
System.out.println("Enter a number. (0 to quit):");
try{
userInput = in.nextDouble();
}
catch(NumberFormatException nfe){
System.out.println("Invalid Number");
}
sum = sum + userInput;
}
答案 0 :(得分:1)
import java.util.InputMismatchException;
import java.util.Scanner;
公共课SamsAdder {
public class SOJavaApplication {
public static void main(String[] args) {
MyClass<Integer> m = new MyClass<Integer>(5);
m.printScreen();
}
}
//T is the generic type
public class MyClass<T> {
T value; //attribute of type T
public MyClass(T value) {
this.value = value;
}
public void printScreen() {
System.out.println(value);
}
public void add(T n) {
value += n;
}
}
}