Exception handling, catch causes while loop to stop

后端 未结 3 1687
醉话见心
醉话见心 2020-12-21 06:52

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.

3条回答
  •  醉话见心
    2020-12-21 07:33

    Put the try catch in the loop like:

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

    Edit: Note that this code causes the loop to infinitely loop on the first line that causes an InputMismatchException. Note accepted answer for the fix to this bug.

提交回复
热议问题