Scanner in = new Scanner(System.in);
int menuItem;
do{
System.out.println("Choose menu item 1,2,3,4,5: ");
menuItem = in.nextInt();
}while(menuItem >5);
//i tried to use this
//while(menuItem >5 || !in.hasNextInt());---> but doesnt work
显示
线程“main”中的异常java.util.InputMismatchException
在此代码中,我想验证menu item not string type
和not more than 5
并重复选择项目菜单,如果输入不是字符串类型且不超过5
但我不知道如何验证输入的字符串。
答案 0 :(得分:2)
在尝试使用输入之前,您需要验证输入,并不保证用户提供整数,甚至是数字作为输入,如果有类似的情况发生,那么这里:
menuItem = in.nextInt();
将尝试从“不可解析为int”的内容中获取整数 然后你会得到一个例外
尝试验证输入,直到用户提供有效的工作...
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int menuItem = -1;
do {
System.out.println("Choose menu item 1,2,3,4,5: ");
while (menuItem == -1) {
try {
menuItem = Integer.parseInt(in.nextLine());
} catch (NumberFormatException e) {
System.out.println("Wrong input");
}
}
} while (menuItem > 5);
}
答案 1 :(得分:0)
试试这个:
import java.util.*;
public class input_mismatch{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int menuItem;
do{
System.out.println("Choose menu item 1,2,3,4,5: ");
menuItem = in.nextInt();
}while(menuItem >5 || in.hasNextInt());
}
}
答案 2 :(得分:0)
作为ΦXoce웃Пepeúpa给出的答案,如果用户输入不大于5,外部while循环将无限运行。
请尝试这样:
1.如果是字符串并且询问用户,将验证数字输入有效数字.2。如果正确,请重复选择chhose菜单项。
package Sample;
import java.util.ArrayList;
import java.util.Scanner;
public class tets
{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int menuItem = 0;
do {
System.out.println("Choose menu item 1,2,3,4,5: ");
try
{
menuItem = Integer.parseInt(in.nextLine());
}
catch (NumberFormatException e)
{
System.out.println("Wrong input, Please enter again");
menuItem=0;
}
} while (menuItem <= 5 && menuItem >=0);
System.out.println("You have entered no > 5 OR no < 0");
System.out.println("EXIT");
}
}
OUTPUT:
Choose menu item 1,2,3,4,5:
2
Choose menu item 1,2,3,4,5:
4
Choose menu item 1,2,3,4,5:
A
Wrong input, Please enter again
Choose menu item 1,2,3,4,5:
-1
Choose menu item 1,2,3,4,5:
6
You have entered no > 5 OR no < 0
EXIT