gpt4 book ai didi

java - 如何仅从键盘获取整数输入,如果输入无效,如何再次询问用户?

转载 作者:行者123 更新时间:2023-11-30 05:13:13 25 4
gpt4 key购买 nike

这是我到目前为止所写的内容,但是当引发异常时,它不会再次要求用户输入。

    do {
System.out.println("Enter the number of stones to play with: ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String temp = br.readLine();
key = Integer.parseInt(temp);
} while (key < 0 && key > 9);

if (key < 0 || key > 10)
throw new InvalidStartingStonesException(key);

player1 = new KeyBoardPlayer();
player2 = new KeyBoardPlayer();
this.player1 = player1;
this.player2 = player2;
state = new KalaGameState(key);
} catch (NumberFormatException nFE) {
System.out.println("Not an Integer");
} catch (IOException e) {
System.out.println(e);
}

最佳答案

一旦抛出 NumberFormatException,您就会跳出循环并向下跳转到 catch。如果您的 try-catch block 位于您的 while 循环中,它将具有您想要的效果为了。您可能需要调整循环的条件。

关于java - 如何仅从键盘获取整数输入,如果输入无效,如何再次询问用户?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2616050/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com