Hy,我写了这段代码,我要求用户输入一个数字:
public static double[] getscores()
{
int numscores=8;
double score[] = new double[numscores];
for (int a=0;a<numscores;a++)
{
Scanner ip=new Scanner(System.in);
System.out.println("Enter a score");
score[a]=ip.nextDouble();
}
return score;
}
在用户意外输入字符串的情况下,如何在不关闭程序的情况下告诉他输入数字?谢谢你
答案 0 :(得分:1)
当用户没有输入double时,你应该捕获抛出的异常,让用户再次尝试插入一个double,并在你试图读取double的那一行继续循环,直到用户实际输入一个双。或者,当用户输入double时,您可以使用while(true)
和break
语句,这可能更干净,但这更具可读性。
public static double[] getscores() {
int numscores = 8;
double score[] = new double[numscores];
for (int a = 0; a < numscores; a++) {
Scanner ip = new Scanner(System.in);
System.out.println("Enter a score");
boolean isDouble = false;
do {
try {
score[a] = ip.nextDouble();
isDouble = true;
} catch (InputMismatchException ex) {
System.out.println("You didn't enter a double, please try again");
}
} while (!isDouble);
}
return score;
}
答案 1 :(得分:0)
用户始终输入字符串; Scanner#nextDouble()
是将String输入解释为double
的便捷方法。
编写一个方法,在输入double之前一直读取输入:
static double readDouble(Scanner scanner) {
double score;
while (true) {
System.out.println("Enter a score");
String input = scanner.nextLine();
try {
score = Double.parseDouble(input);
break;
} catch (NumberFormatException e) {
System.out.println("'" + input + "' is not a valid score");
}
}
return score;
}
然后从你的循环中调用它:
score[a] = readDouble(ip);
答案 2 :(得分:-1)
快速但“肮脏”的解决方案是使用try-catch:
public static double[] getscores() {
int numscores = 8;
double score[] = new double[numscores];
for (int a = 0; a < numscores; a++) {
Scanner ip = new Scanner(System.in);
System.out.println("Enter a score");
try{
score[a] = ip.nextDouble();
} catch(InputMismatchException ime) {
System.out.println("Wrong input");
a--;
}
}
return score;
}