/ **要更改此许可证标题,请在“项目属性”中选择“许可证标题”。*要更改此模板文件,请选择工具|范本*并在编辑器中打开模板。* /包验证输入;
import java.util.Scanner;
/ **** @作者阿卜杜勒* /公共类ValidatingInput {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
// Declare variables
int number = 0;
int lowerbound = 5;
int upperbound =10;
//Prompt the user to enter an interger between 5 and 10
System.out.println("Please enter a interger int between 5 and 10");
while (!s.hasNextInt()) {
System.out.println("Not an int");
s.next();
}
number = s.nextInt();
if (number<= lowerbound || number >= upperbound){
System.out.println("out bound");
number++;
}else{
System.out.println("you entered");
s.next();
}number = s.nextInt();
}
}
我认为这里有两个问题:
number = s.nextInt()
(等待更多输入),然后停止(从main
返回)。您需要另一个循环,直到用户输入有效整数为止。number = s.nextInt()
从扫描仪读取该整数。如果整数在范围内,请调用s.next()
,然后调用number =
s.nextInt()*again*. Both calls look suspicious/wrong: you already have the integer to be read in variable
number. There is no need to read any more information from the scanner. In fact, the calls to
s.next()and
s.nextInt()`,直到输入更多数据为止。 在第一行number = s.nextInt()
之后,您不应再呼叫s.nextXXX()
。