我正在编写一个程序,它接受程序中的两个整数,nextInt();
并将其包装在一个try catch
块中以阻止错误的输入,例如双精度数或字符。
当输入多个错误输入时,循环会重复相同的次数。我认为这是因为我scan.next()
必须循环足够多的时间才能捕获没有错误的错误输入。有没有办法在第一次运行时知道这个数字,以便循环运行多次?
在输出中,
if(cont == 'N') System.out.print("\nPlease re-enter\n\t:");
将输出并镜像写入不匹配输入的次数。也就是说,如果我输入 3 3.3 它将重复一次,如果输入 s 3.3 2.5 它将重复三次。
我尝试将循环scan.next()
默认为十次,但太过分了,我必须输入额外的 8 个字符才能再次开始阅读。也许是一个while循环,但它的条件是什么,我试过while(scan.next() != null){}
了,但那个条件从未停止过。
//input error checking
char cont = 'Y';
do{
if(cont == 'N')
System.out.print("\nPlease re-enter\n\t:");
cont = 'Y';
/* to stop the accidential typing of things other
* than integers from being accepted
*/
try{
n1 = scan.nextInt();
n2 = scan.nextInt();
}catch(Exception e){
cont = 'N'; //bad input repeat loop
scan.next();//stops infinite loop by requesting Scanner try again
}
} while(cont == 'N');//do loop while told N for continue