我需要输入数组的值是1-100,而不是任何字母。我试图设置一个临时值,该值将捕获之前不是1-100的数字,但似乎无法使其正常工作。我遇到的问题是,如果输入字母,程序将关闭。任何帮助,将不胜感激。
public class FocusGroup {
static Scanner scan = new Scanner(System.in);
public static void main(String args[]) {
double tempValue = scan.nextDouble();
if (tempValue > 100 || tempValue < 0) {
scan.nextDouble();
System.out.println("Invalid");
} else {
while (true) {
try {
double sumFocus = 0;
double[] arrayFocus = new double[2];
for (int i = 0; i < 2; i++) {
arrayFocus[i] = scan.nextDouble();
}
for (double num : arrayFocus) {
sumFocus = sumFocus + num;
}
}
catch (InputMismatchException e) {
System.out.println("Invalid input");
scan.nextLine();
}
}
}
}
}
最佳答案
在catch语句中,您使用scan.nextLine()
,但应像在主循环中一样使用scan.nextDouble()
。也就是说,您要接受双精度作为输入。
另外,您的try / catch语法似乎是错误的。您想捕获可能由用户输入引起的错误;因此,您需要在用户在try块中输入内容的地方添加代码。见下文:
try {
double tempValue = scan.nextDouble();
//this loop will keep spinning, until tempValue is valid
while (tempValue > 100d || tempValue < 0d) {
System.out.println("Invalid. Try again. Range is 0 - 100");
tempValue = scan.nextDouble();
}
//this loop will spin forever (There is nothing to terminate it)
while (true) {
double sumFocus = 0;
double[] arrayFocus = new double[2];
for (int i = 0; i < 2; i++) {
arrayFocus[i] = scan.nextDouble();
}
for (double num : arrayFocus) {
sumFocus = sumFocus + num;
}
}
}
catch (InputMismatchException e) {
System.out.println("Invalid input");
scan.nextDouble(); //this doesn't do anything. The value is not assigned to any variable
}
使用上述代码,当用户输入无效字符(例如字母)时,程序将停止。为什么?因为catch在无限循环之外,这使您的程序计数器移出循环,并且当执行catch语句中的代码时,您的程序也将在结束时终止。
您可以做的是这样的:
static double validValueWithRange(Double min, Double max){
Scanner s = new Scanner(System.in);
System.out.println("Enter a valid value for a 'double': ");
double value;
try {
value = s.nextDouble();
if(value > max || value < min){
System.out.println("Invalid. Try again. Range is 0 - 100");
return validValueWithRange(min, max);
}
}
catch (InputMismatchException e) {
System.out.println("Invalid input. Try again.");
return validValueWithRange(min, max);
}
return value;
}
static double validValue(){
Scanner s = new Scanner(System.in);
System.out.println("Enter a valid value for a 'double': ");
double value;
try {
value = s.nextDouble();
}
catch (InputMismatchException e) {
System.out.println("Invalid input. Try again.");
return validValue();
}
return value;
}
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
double tempValue = validValueWithRange(0d, 100d);
while (true) {
System.out.println("Now entering endless while loop");
double sumFocus = 0;
double[] arrayFocus = new double[2];
for (int i = 0; i < 2; i++) {
arrayFocus[i] = validValue();
}
for (double num : arrayFocus) {
sumFocus = sumFocus + num;
}
}
}