Closed. This question needs details or clarity。它当前不接受答案。
想改善这个问题吗?添加详细信息并通过editing this post阐明问题。
6个月前关闭。
如果不是整数,则捕获异常。请尝试以下操作:
想改善这个问题吗?添加详细信息并通过editing this post阐明问题。
6个月前关闭。
int[] intRange1 = {};
intNum = getValidInt(sIn, "Please enter a whole number: ",
"Invalid response. Only whole numbers are acceptable.", intRange1);
System.out.println("The whole number your entered was: " + intNum);
System.out.println("Now we will test your whole number in a math equation...");
System.out.printf("Adding 10 to your whole number would be: 10 + %d = %d.\n\n", intNum, (intNum + 10));
// Get an integer within a range from the user
int[] intRange2 = { 10, 50 };
intNum = getValidInt(sIn, "Please enter a whole number between 10 and 50: ",
"Invalid response. Only whole numbers between 10 and 50 are acceptable.", intRange2);
System.out.println("The whole number your entered was: " + intNum);
System.out.println("Now we will test your whole number in a math equation...");
System.out.printf("Adding 10 to your whole number would be: 10 + %d = %d.\n\n", intNum, (intNum + 10));
}
/*
* making the method I can get it to validate the first part but I can not get
* it to do the part with the range
*/
public static int getValidInt(Scanner sIn, String question, String warning, int[] range) {
boolean valid = false;
int validNumber = 0;
do {
System.out.println("Please enter a whole number: ");
String number = sIn.nextLine();
try {
validNumber = Integer.parseInt(number);
valid = true;
} catch (NumberFormatException e) {
System.out.println("Invalid response. Only whole numbers are acceptable.");
valid = false;
} // end of try/catch block
} while (!valid);// end of do while
}
最佳答案
为什么不做
int v = SIn.nextInt();
如果不是整数,则捕获异常。请尝试以下操作:
Scanner sIn = new Scanner(System.in);
int r = getValue(sIn, 10, 40);
System.out.println("You entered " + r);
static int getValue(Scanner sIn, int low, int high) {
String msg = "Please enter a number between %d and %d%n";
while (true) {
System.out.printf(msg, low, high);
System.out.print("Enter: ");
try {
int v = sIn.nextInt();
if (v >= low && v <= high) {
sIn.nextLine();//clear input buffer
return v;
}
System.out.printf("Number out of range (%d).", v);
}
catch (InputMismatchException e) {
System.out.printf("Illegal input type (%s)%n", sIn.nextLine());
}
}
}
关于java - 麻烦找出范围是否为空,以便让我继续进行代码。 JAVA ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58884220/
10-12 02:21