Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/324.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Try catch块,catch块不会重新提示用户输入新值_Java_Try Catch - Fatal编程技术网

Java Try catch块,catch块不会重新提示用户输入新值

Java Try catch块,catch块不会重新提示用户输入新值,java,try-catch,Java,Try Catch,我是Java新手,想问你一个问题 我编写了下面的代码,其中“numOfThreads”应该由用户通过控制台分配一个有效的int值 但是,我希望得到这样一个结果:如果输入不正确,我们进入catch块,则应重新提示用户输入“numothreads”,直到其类型和范围正确 出于某种原因,我似乎进入了无限循环。你能帮忙吗?谢谢:) 这不是因为nextInt试图使用最后一个令牌。当存在无效输入时,它不能使用它。因此,下面的nextInt调用也无法使用它。在numOfThreads=keyboard.nex

我是Java新手,想问你一个问题

我编写了下面的代码,其中“
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
}