如何为输入的不同类型的数据显示不同的消息? 我只希望用户能够输入一个整数,但如果他们输入其他内容,那么我想要为每种类型添加自定义消息。 例如,
目前我正在使用此代码,只允许我显示一条消息(如果它不是整数
)printMenuOption();
if (!sc.hasNextInt()){
System.out.println("Please enter a number from 1 to 10");
sc.nextLine();
}else{
returnDataMenu(sc.nextInt());
}
答案 0 :(得分:0)
我希望这会对你有所帮助。
Scanner myInput = new Scanner(system.in);
do {
printMenuOption();
if (!myInput.hasNextInt()){
if(myInput.hasNextDouble()){
System.out.println("You can not use a decimal number!");
System.out.println("Please try again, choose a number from 1 to 10.");
}else if(myInput.nextLine().length() <= 1){
System.out.println("You can not use a character as an entry");
System.out.println("Please try again, choose a number from 1 to 10.");
}else if(myInput.nextLine().length() > 1){
System.out.println("You can not enter a string");
System.out.println("Please try again, choose a number from 1 to 10.");
}
else{
System.out.println("Please enter a number from 1 to 10");
userInput = myInput.nextLine();
}
}
else{
returnDataMenu(myInput.nextInt());
}
} while (cont == true);
答案 1 :(得分:0)
如下所示,它将解决您的问题,
while (sc.hasNext()) {
if (sc.hasNextInt()) {
returnDataMenu(sc.nextInt());
} else if (sc.hasNextLong()) {
System.out.println("You can't enter a long number, please use a whole number from 1-10");
} else if (sc.hasNextDouble()) {
System.out.println("You can't enter a number with a decimal, please use a whole number from 1-10");
} else if (sc.hasNextBoolean()) {
System.out.println("You can't enter a boolean, please use a whole number from 1-10");
} else if (sc.next() != null) {
System.out.println("You can't enter a string, please use a whole number from 1-10");
} else if (sc.nextLine().length() <= 1) {
System.out.println("You can't enter a char, please use a whole number from 1-10");
}
}
java.util.Scanner有许多hasNextXXX方法可用于验证输入。以下链接概述了所有这些内容:
http://docs.oracle.com/javase/6/docs/api/java/util/Scanner.html#hasNext%28java.lang.String%29