我需要验证用户的输入,以便输入的值为double
或int
;然后将int
/ double
值存储在数组中,并在用户输入无效数据时显示错误消息。
由于某些原因,如果用户输入无效数据,我的代码会崩溃 您能否请查看下面的代码并告诉我可能出现的问题?
public static double[] inputmethod() {
double list[] = new double[10];
Scanner in = new Scanner(System.in);
double number;
System.out.println("please enter a double : ");
while (!in.hasNextDouble()) {
in.next();
System.out.println("Wrong input, Please enter a double! ");
}
for (int i = 0; i < list.length; i++) {
list[i] = in.nextDouble();
System.out.println("you entered a double, Enter another double: ");
}
return list;
}
答案 0 :(得分:1)
对于验证用户双重或不执行如下操作:
public class TestInput {
public static double[] inputmethod() {
double list[] = new double[10];
Scanner in = new Scanner(System.in);
double number;
System.out.println("please enter a double : ");
for (int i = 0; i < list.length; i++) {
while (!in.hasNextDouble()) {
in.next();
System.out.println("Wrong input, Please enter a double! ");
}
list[i] = in.nextDouble();
System.out.println("you entered a double, Enter another double: ");
}
return list;
}
public static void main(String args[]) {
inputmethod();
}
}
答案 1 :(得分:0)
你基本上已经走上了正轨!您所要做的就是将while loop
用于验证用户输入for loop
。你的代码看起来应该是这样的。
public class InputTest{
public static double[] inputmethod() {
double list[] = new double[10];
Scanner in = new Scanner(System.in);
double number;
System.out.print("Please enter a double: ");
for (int i = 0; i < list.length; i++) {
while(!in.hasNextDouble()){
in.next();
System.out.print("Wrong input! Please enter a double: ");
}
System.out.print("You entered a double! Enter another double: ");
list[i] = in.nextDouble();
}
return list;
}
public static void main(String args[]){
double list[] = inputmethod();
}
}