我是Java的新手,我正在程序中研究一种方法,该方法检查用户输入是否在边界内,而不是空值(零),不是字母和正数。所以最初我在此方法中合并了两个 while 循环来检查这些输入的有效性,但我想在一个循环中简化它。当我在几次输入后输入一个字母(例如 a)时,我收到错误,我相信这是由于两个不同的 while 循环使其更加复杂。有人可以帮我解决这个问题吗?
public static void valid(String s, int max)
{
while(sc.hasNextInt() == false) {
System.out.println("That is not correct. Try again:");
sc.nextLine();
}
int value;
while((value= sc.nextInt()) > max || (value= sc.nextInt()) <= 0){
System.out.println("That is not correct. Try again: ");
sc.nextLine();
}
sc.nextLine();
return;
}
你有:
int value;
while((value= sc.nextInt()) > max || (value= sc.nextInt()) <= 0){
System.out.println("That is not correct. Try again: ");
sc.nextLine();
}
这是两次sc.nextInt()
,所以value
在这两种情况下不一定具有相同的值,它也要求你两次提供数字。
修复程序如下所示:
int value;
while((value = sc.nextInt()) > max || value <= 0) {
System.out.println("That is not correct. Try again: ");
sc.nextLine();
}
这会让它变得更好,但你仍然有问题。如果value
大于 max
,则循环将再次迭代调用nextInt()
但这次您没有检查hasNextInt()
。这就是为什么你最好把所有东西都放在一个循环中。像这样:
public static void valid(String s, int max) {
while(true) {
if(!sc.hasNextInt()) { //this is the same as sc.hasNextInt() == false
System.out.println("That is not correct. Try again:");
sc.nextLine();
continue; //restart the loop again
} else {
int value = sc.nextInt();
if(value > max || value <= 0) {
System.out.println("That is not correct. Try again:");
sc.nextLine();
continue; //restart the loop from the top - important!
} else {
extendedValidation(value, s);
return;
}
}
}
}
尝试更像(伪代码)的东西:
while valid input not yet received:
if input is an integer:
get integer
if in range:
set valid input received
skip rest of line
extended validation
稍加思考,您应该能够使用一个"打印错误消息"语句。 但是使用两个可以说更好;它可以告诉用户他们做错了什么。
String s
参数的目的是什么?您是否应该检查它而不是扫描仪输入?
另外,不要对混合nextInt()
和nextLine()
感到惊讶。
我更喜欢在验证之前使用 do-while 循环进行输入。
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int max = 1000;
int val = -1;
String in;
do {
// Read a string
System.out.print("Enter a number: ");
in = input.nextLine();
// check for a number
try {
val = Integer.parseInt(in);
} catch (NumberFormatException ex) {
// ex.printStackTrace();
System.out.println("That is not correct. Try again.");
continue;
}
// check your bounds
if (val <= 0 || val > max) {
System.out.println("That is not correct. Try again.");
continue;
} else {
break; // exit loop when valid input
}
} while (true);
System.out.println("You entered " + val);
// extendedValidation(value, in);
}
简单来说,我想说这更接近您正在寻找的内容......
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
final int MIN = 0;
final int MAX = 10;
Scanner sc = new Scanner(System.in);
int value = -1;
boolean valid;
do {
valid = sc.hasNextInt();
if (valid) {
value = sc.nextInt();
valid = value > MIN && value < MAX;
}
if (!valid) {
System.out.println("Invalid!");
sc.nextLine();
}
} while (!valid);
System.out.println("Valid Value: " + value);
}
}
您应该能够抽象此代码以满足您的要求。