我希望我的程序告诉用户如果他输入一个非整数,他应该再试一次,而不是像现在一样终止整个main方法。问题部分的伪代码:
int integer = input.nextInt();
If (user types in a non-integer) {
("you have entered a false value, please retry");
then let's user enter int value
else {
assign nextint() to integer and continue
}
答案 0 :(得分:8)
您可以使用a while
loop重新执行该部分代码,直到用户输入正确的整数值。
do {
input = read user input
} while(input is not an integer)
您似乎使用的是Scanner
,因此您可以use the hasNextInt
method:
while (!input.hasNextInt()) {
let user know that you are unhappy
input.next(); //consume the non integer entry
}
//once here, you know that you have an int, so read it
int number = input.nextInt();
答案 1 :(得分:0)
这假设您担心用户输入的内容不是输入的整数:
public static void main(String[] args) {
Integer integer = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter an integer:");
String line = sc.next();
integer = tryParse(line);
while(integer == null){
System.out.print("The input format was incorrect, enter again:");
integer = tryParse(sc.next());
}
int value = integer.intValue();
}
public static Integer tryParse(String text){
try{
return new Integer(text);
} catch
(NumberFormatException e){
return null;
}
}