0

所以我在这里写代码只是为了好玩,但我遇到了一个我似乎无法修复的错误。这段代码应该接受一个 int ......起初我在 while 循环中单独使用 hasNextInt() 来尝试确保我得到正确的输入,但命运会这样......我得到了例外。然后我添加了一个尝试捕获它想也许我做错了什么......但我仍然得到同样的错误。我不知道这里有什么问题。这实际上是我第一次使用 try catch 块(仍然是一个菜鸟)。它对我来说看起来不错,我查看了在线文档并进行了一些小型研究,但无济于事。谁能确定这里有什么问题?一探究竟:

do{
    System.out.println("How much AP do you want to allocate towards HP? ");

    try {//added try catch... still throwing the exception..

        while(!in.hasNextInt()){//this should've been enough, apparently not
            System.out.println("That is not a valid input, try again.");
            in.nextInt();
            }
    } catch (InputMismatchException e) {
        System.out.print(e.getMessage()); //trying to find specific reason.
    }
    hpInput = in.nextInt();
}while(hpInput < 0 || hpInput > AP);

如果我输入了一个字符串,它会给我“这不是一个有效的输入,再试一次”。行..但异常仍然会在之后发生,而不是仅仅循环直到检测到实际的 int ......帮助 plz..

4

2 回答 2

2

你的while循环应该是这样的

while(!in.hasNextInt()){ // <-- is there an int?
    System.out.println("That is not a valid input, try again.");
    // in.nextInt(); // <-- there is not an int...
    in.next(); // <-- this isn't an int.
}

因为Scanner没有int.

于 2015-02-26T03:02:11.237 回答
0

在输入某些内容之前,您无法真正验证中的值Scanner,但是一旦输入,验证它为时已晚......

相反,您可以使用一秒钟Scanner来验证String您通过键盘从用户那里获得的结果,例如

Scanner kbd = new Scanner(System.in);
int result = -1;
do {
    System.out.println("How much AP do you want to allocate towards HP? ");
    String value = kbd.nextLine();
    Scanner validate = new Scanner(value);
    if (validate.hasNextInt()) {
        result = validate.nextInt();
    }
} while (result < 0);
于 2015-02-26T03:01:43.503 回答