That uses hasNextInt() before actually reading the input, I tried to put this check inside while loop in the same place with n<=0 like thiswhile ( (n<=0)||(sca.hasNextInt() )) { ....}但是它响应错误,指出变量 n 与该方法不兼容.那么有什么办法可以克服这种情况?But it responded with error that variable n is not compatible with that method.So is there any way to overcome such thing?推荐答案首次调用 nextInt()也会导致异常,如果您不检查输入是否为int 类型.First invocation of nextInt() also can result in an exception, if you do not check whether the input is of int type.以下希望可以解决您的问题.Hope below will resolve your issue.Scanner sca = new Scanner(System.in);boolean incorrectInput = true;int userInput = -1; // initialize as a negativewhile (incorrectInput) { if (sca.hasNextInt()) { int n = sca.nextInt(); if (n < 0) { System.err.println("error_1"); } else { // do anything else userInput = n; incorrectInput = false; } } else { sca.next(); }}if (!incorrectInput) { System.out.println("UserInput = " + userInput);} 这篇关于检查输入值是否为整数类型java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 阿里云证书,YYDS!
05-24 18:39