Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
407 views
in Technique[技术] by (71.8m points)

java - Exception handling, catch causes while loop to stop

I have a file that I need to read, print out the integers, catch exception and continue with the next integer to display, and so on until there are no more integers.

The file contains: 12 5 sd 67 4 cy

I want it to display:

12
5
Input error
67
4
Input error

However, it only gives me 12, 5, followed by input error, and it stops. I've tried putting everything into a while loop and it loops endlessly with the input exception.

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!");
      }    
  }

 }

What am I missing so that the loop continues reading the next int and so on?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The try/catch block needs to be inside the loop.

When an exception is thrown, control breaks out as far as it can until it encounters a catch block, which in your case, is outside of your loop.

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!");  
    }

}

I've tried putting everything into a while loop and it loops endlessly with the input exception.

You mentioned that you tried this already. I need more details on the problem you encountered because this is the right way to do it. Off the top of my head, just a hunch, is that perhaps reader.nextInt() does not advance the reader's position in the file when the exception occurs and therefore calling nextInt again and again reads the same non-integer chunk.

Perhaps your catch block needs to call reader.getSomethingElse? Like reader.next()?

This is an idea and I have not tested it:

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!");  
    }

}

[Edit 9:32PM]

I am correct about advancing the reader.

Per the Java doc for Scanner:

Scans the next token of the input as an int. This method will throw InputMismatchException if the next token cannot be translated into a valid int value as described below. If the translation is successful, the scanner advances past the input that matched.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...