用户输入验证的所有可能性
我想确保用户只输入一个int,并且范围从10到20
当我第一次输入一个超出范围的int时,我最终得到一个错误然后输入一个字符串。我不确定如何继续要求用户继续输入,直到数字落在指定的范围内。 任何帮助,将不胜感激!用户输入验证的所有可能性
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int width = 0;
int height = 0;
System.out.println("Welcome to Mine Sweeper!");
System.out.println("What width of map would you like (10 - 20): ");
//width = scnr.nextInt()
while (!scnr.hasNextInt()) {
System.out.println("Expected a number from 10 to 20");
scnr.next();
}
do {
width = scnr.nextInt();
if (width < 10 || width > 20) {
System.out.println("Expected a number from 10 to 20");
//width = scnr.nextInt();
}
} while (width < 10 || width > 20);
}
试试这个:
Scanner scnr = new Scanner(System.in);
int width = 0;
int height = 0;
System.out.println("Welcome to Mine Sweeper!");
while(true)
{
System.out.println("What width of map would you like (10 - 20): ");
try{
width = scnr.nextInt();
System.out.println(width);
if (width < 10 || width > 20)
{
System.out.println("Expected a number from 10 to 20");
}
else
break;
}catch(Exception e)
{
System.out.println("Expected a number from 10 to 20");
scnr.next();
}
}
scnr.close();
有没有办法做到这一点,而不使用try和catch? – JRob
@JRob如果你不使用'try/catch'你将在用户输入String而不是int时如何处理异常? 也检查更新的代码。 –
这应该做你想要什么:
while (scnr.hasNext()) {
if (scnr.hasNextInt()) {
width = scnr.nextInt();
if (width >= 10 && width <= 20) {
break;
}
}else{
scnr.next();
}
System.out.println("Expected a number from 10 to 20");
}
System.out.println("width = " + width);
据我了解,你是想只接受的范围之间的整数值10和20包括在内。如果输入了字符或字符串,则需要打印出一条消息并继续执行。如果是这样,那么这应该接近你想要的。我原本打算用try-catch声明来回答这个问题,但我注意到你回答了另一个答案,并说你想要一个与使用try-catch不同的方法。此代码不是100%功能;你将不得不调整一些东西,但它非常接近你正在寻找的东西,我认为没有使用try-catch声明。
public static void main(String args[])
{
Scanner scanner = new Scanner(System.in);
int width = 0;
int height = 0;
int validInput = 0; //flag for valid input; 0 for false, 1 for true
System.out.println("Welcome to Mine Sweeper!");
System.out.println("What width of map would you like (10 - 20): ");
while (validInput == 0) //while input is invalid (i.e. a character, or a value not in range
{
if (scanner.hasNextInt())
{
width = scanner.nextInt();
if (width >= 10 && width <= 20)
{
validInput = 1; //if input was valid
}
else
{
validInput = 0; //if input was invalid
System.out.println("Expected a number from 10 to 20.");
}
}
else
{
System.out.println("You must enter integer values only!");
validInput = 0; //if input was invalid
}
scanner.next();
}
}
请发表您的错误! – phpdroid