0

我正在编写一个程序,它接受程序中的两个整数,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
4

4 回答 4

1

不确定您希望代码做什么。通过阅读您发布的内容,我假设您希望用户输入 2 个整数,如果他/她不想提示他/她重新输入某些内容,直到他/她输入 2 个整数。如果是这种情况,我会添加

scan = new Scanner(br.readLine());

在此 if 语句之后:

if(cont == 'N') {System.out.print("\nPlease re-enter\n\t:");}

这将解决您的循环问题

于 2012-08-23T13:22:41.413 回答
0

第一次尝试 :

将异常捕获中的行从

scan.next();

while(scan.hasNext()){
    scan.next();
}
于 2012-08-23T09:21:10.510 回答
0

您可以尝试在 catch 块中执行以下操作:

while(scan.hasNext())
    scan.next();
于 2012-08-23T09:21:35.063 回答
0

使它成为一种方法并使用该方法进行操作。
像这样的某事:

        // do it until getting two Integers
    boolean isItInteger = false;
    while (isItInteger == false) {
        isItInteger = getInt();
    }
    .
    .
    .
        // your method for getting two Integers
    public static boolean getInt() {
        try {
            Scanner sc = new Scanner(System.in);
            n1 = sc.nextInt();
            n2 = sc.nextInt();
        } catch (Exception e) {
            System.out.println("Please re-enter");
            return false;
        }
        return true;
    }
于 2012-08-23T09:23:09.997 回答