0

我希望我的程序告诉用户,如果他输入了一个非整数,他应该再试一次,而不是像现在这样终止整个 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
}
4

2 回答 2

8

您可以使用循环while重新执行该部分代码,直到用户输入正确的整数值。

do {
    input = read user input
} while(input is not an integer)

看来您正在使用 a Scanner,因此您可以使用该hasNextInt方法

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();
于 2012-09-28T16:10:06.523 回答
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;
    }
}
于 2012-09-28T16:24:24.280 回答