Java Try catch块,catch块不会重新提示用户输入新值
我是Java新手,想问你一个问题 我编写了下面的代码,其中“Java Try catch块,catch块不会重新提示用户输入新值,java,try-catch,Java,Try Catch,我是Java新手,想问你一个问题 我编写了下面的代码,其中“numOfThreads”应该由用户通过控制台分配一个有效的int值 但是,我希望得到这样一个结果:如果输入不正确,我们进入catch块,则应重新提示用户输入“numothreads”,直到其类型和范围正确 出于某种原因,我似乎进入了无限循环。你能帮忙吗?谢谢:) 这不是因为nextInt试图使用最后一个令牌。当存在无效输入时,它不能使用它。因此,下面的nextInt调用也无法使用它。在numOfThreads=keyboard.nex
numOfThreads
”应该由用户通过控制台分配一个有效的int值
但是,我希望得到这样一个结果:如果输入不正确,我们进入catch块,则应重新提示用户输入“numothreads
”,直到其类型和范围正确
出于某种原因,我似乎进入了无限循环。你能帮忙吗?谢谢:)
这不是因为
nextInt
试图使用最后一个令牌。当存在无效输入时,它不能使用它。因此,下面的nextInt
调用也无法使用它。在numOfThreads=keyboard.nextLine()之前写一个keyboard.nextLine
代码>你很好
catch(Exception e){
System.out.println("Entry is not correct and the following exception is returned: " + e);
// this consumes the invalid token now
keyboard.nextLine();
numOfThreads = keyboard.nextInt(); // It wasn´t able to get the next input as the previous was still invalid
// I´d still rewrite it a little bit, as this keyboard.nextInt is now vulnerable to throw a direct exception to the main
}
如果nextInt()。。。所以再次调用nextInt
只会再次抛出。您的try/catch非常无用。。。如果你重新编程时他们输入了错误的输入怎么办?
catch(Exception e){
System.out.println("Entry is not correct and the following exception is returned: " + e);
// this consumes the invalid token now
keyboard.nextLine();
numOfThreads = keyboard.nextInt(); // It wasn´t able to get the next input as the previous was still invalid
// I´d still rewrite it a little bit, as this keyboard.nextInt is now vulnerable to throw a direct exception to the main
}