gpt4 book ai didi

java - 来自扫描仪的 hasNextInt() 行为异常

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

我有一个等待数字 (int) 的非常简单的循环,只要该数字不是 exitOption 它就不会离开循环,但是我得到了一个意外错误,我没有不知道是什么原因造成的。

编辑

添加另一个片段以便您可以编译

public static void main(String[] args) throws   FileNotFoundException,
SecurityException,
IOException,
ClassNotFoundException {


while (controller.selectOptionMM());

/编辑

public boolean selectOptionMM() throws  SecurityException, 
FileNotFoundException,
IOException {

int cmd = ui.getExitOption();

ui.mainMenu();
cmd = utils.readInteger(">>> "); // this is my problem, right here
// code in next snippet
while (cmd <1 || cmd > ui.getExitOption()) {
System.out.println("Invalid command!");
cmd = utils.readInteger(">>> ");
}

switch (cmd) {
case 1:
case 2:
case 3:
case 4: this.repository.close();
return true;
case 5: return false;
}

return false;
}

这里是失败的地方:

public int readInteger(String cmdPrompt) {
int cmd = 0;
Scanner input = new Scanner(System.in);

System.out.printf(cmdPrompt);
try {
if (input.hasNextInt())
cmd = input.nextInt(); // first time it works
// Second time it does not allow me to input anything
// catches InputMissmatchException, does not print message
// for said catch
// infinitely prints "Invalid command" from previous snippet

} catch (InputMismatchException ime) {
System.out.println("InputMismatchException: " + ime);
} catch (NoSuchElementException nsee) {
System.out.println("NoSuchElementException: " + nsee);
} catch (IllegalStateException ise) {

} finally {
input.close(); // not sure if I should test with if (input != null) THEN close
}


return cmd;
}

第一次 我通过了槽,它读取数字没问题。现在,如果数字不是 5(在本例中为 exitOption),它会再次通过 readInteger(String cmdPrompt),除了这次它会跳转到 catch (InputMismatchException ime)(调试) 除了它不打印该消息而只是跳转到 Error, input must be numberInvalid command

我的输入缓冲区中是否有东西卡住了,我可以刷新它吗,为什么它(输入缓冲区)卡住了(带有随机数据)???

我会再次尝试调试,看看我的输入缓冲区中卡住了什么,如果我能弄清楚如何查看的话。

最佳答案

问题出在对 input.close() 的调用中 - 这会导致关闭基础输入流。当被关闭的输入流是 System.in 时,就会发生不好的事情(即,您无法再从标准输入读取数据)。删除这一行应该没问题。

关于java - 来自扫描仪的 hasNextInt() 行为异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14060165/

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