异常处理,捕获导致循环停止

and*_*as7 2 java exception

我有一个我需要读取的文件,打印出整数,捕获异常并继续显示下一个整数,依此类推,直到没有更多的整数.

该文件包含:12 5 sd 67 4 cy

我希望它显示:

12
5
输入错误
67
4
输入错误

但是,它只给我12,5,然后输入错误,它停止.我已经尝试将所有内容放入while循环中,并且无限循环地输入异常.

public static void readNumbers()
 {

    File inputFile = new File ("C:/users/AC/Desktop/input.txt");
     try
     {
         Scanner reader = new Scanner(inputFile);
         while(reader.hasNext())
         {
                int num = reader.nextInt();
                System.out.println("Number read: " +num);
            } 
      }
      catch (InputMismatchException e)
      {
                System.out.println("Input error ");
      }
      catch (FileNotFoundException e2)
      {
          System.out.println("File not found!");
      }    
  }

 }
Run Code Online (Sandbox Code Playgroud)

我错过了什么,以便循环继续读取下一个int等等?

Bra*_*don 5

try/catch块需要在循环内部.

抛出异常时,控制会尽可能地突破,直到遇到catch块(在您的情况下,在您的循环之外).

public static void readNumbers()
{

    File inputFile = new File ("C:/users/AC/Desktop/input.txt");
    try {
        Scanner reader = new Scanner(inputFile);
        while(reader.hasNext())
        {
            try
            {
                int num = reader.nextInt();
                System.out.println("Number read: " +num);
            }
            catch (InputMismatchException e)
            {
                System.out.println("Input error ");
            }
        }
    }
    catch (FileNotFoundException e2)
    {
        System.out.println("File not found!");  
    }

}
Run Code Online (Sandbox Code Playgroud)

我已经尝试将所有内容放入while循环中,并且无限循环地输入异常.

你提到你已经尝试过了.我需要更多关于您遇到的问题的详细信息,因为这是正确的方法.在我的脑海中,只是预感,或许reader.nextInt()在发生异常时不会提升读者在文件中的位置,因此再次调用nextInt会读取相同的非整数块.

也许你的catch块需要调用reader.getSomethingElse?喜欢reader.next()?

这是一个想法,我没有测试过:

public static void readNumbers()
{

    File inputFile = new File ("C:/users/AC/Desktop/input.txt");
    try {
        Scanner reader = new Scanner(inputFile);
        while(reader.hasNext())
        {
            try
            {
                int num = reader.nextInt();
                System.out.println("Number read: " +num);
            }
            catch (InputMismatchException e)
            {
                System.out.println("Input error ");
                reader.next();   // THIS LINE IS NEW
            }
        }
    }
    catch (FileNotFoundException e2)
    {
        System.out.println("File not found!");  
    }

}
Run Code Online (Sandbox Code Playgroud)

[编辑9:32 PM]

我推进读者是正确的.

根据Scanner的Java文档:

将输入的下一个标记扫描为int.如果下一个标记无法转换为有效的int值,则此方法将抛出InputMismatchException,如下所述.如果翻译成功,扫描仪将超过匹配的输入.

http://docs.oracle.com/javase/7/docs/api/