繁体   English   中英

我在Java中的扫描仪类中遇到问题

[英]I am Facing issues in Scanner Class in java

如果我输入了错误的输入(例如,如果我输入String而不是Integer),则循环未结束,则下次将无法获得输入。 我在这里(下)附上整个程序。 你能帮忙吗? 提前致谢!!!

import java.util.InputMismatchException;
import java.util.Scanner;

/**
 * If we enter the wrong input(example , if we enter sting instead of integer) it goes unending loop
 * 
 * @author Nithish
 *
 */
public class Sample2 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        for (int i = 0; i < 1; i++) {
            try {
                System.out.println("Enter the value");
                int obj = scanner.nextInt();
                System.out.println(obj);
            } catch (InputMismatchException e) {
                i--;
                e.printStackTrace();
            }
        }
    }
}

在InputMismatchException上,您正在执行i--,因此修改了循环条件以防止没有所需输入的情况下循环结束。 如果您阅读Scanner.nextInt()的API文档,则应注意以下几点:

如果翻译成功,则扫描程序将前进经过匹配的输入。

这意味着如果输入不能转换为int,则扫描仪不会前进。 因此,在下次调用nextInt()时,它将重新读取完全相同的非整数输入,并再次失败。 在尝试再次获取int之前,您需要阅读该非整数标记。

同样,不要弄乱循环内部的循环索引,因为这可能会引起问题。 取而代之的是使用while循环,此循环从现在开始的3个月更加干净,调试起来也更加容易:

import java.util.InputMismatchException;
import java.util.Scanner;

public class Sample2 {
   public static void main(String[] args) {
      Scanner scanner = new Scanner(System.in);
      boolean done = false;
      int result = 0;

      while (!done) {
         try {
            System.out.print("Enter the value: ");
            String temp = scanner.nextLine();
            result = Integer.parseInt(temp);
            done = true;
         } catch (NumberFormatException e) {
            System.out.println("Please only enter integer data");
         }
      }
      scanner.close();
   }
}
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < 3; i++) {
    try {
        System.out.println("Enter the value");
        int obj = scanner.nextInt();
        System.out.println(obj);
    } catch (InputMismatchException e) {
        i--;
        //e.printStackTrace();
        scanner.nextLine(); //you can add this here.
        //scanner.next(); you can also use this 
    }
}

那下面呢?

Scanner sc = new Scanner(System.in);
while (!sc.hasNext()) {
  System.out.println("Enter the value");
   if (src.hasNextInt()) {
      i = src.nextInt();
      System.out.println("Thank you! (" + i+ ")");
   }
      else
   {
      System.out.println("Please only int");
   }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM