How to type a string to end a integer Scanning process in Java

前端 未结 3 439
闹比i
闹比i 2021-01-27 03:21

I would like to use Scanner to scan any number of integer then get the average. Before I stop, I would like to type \"END\".

The code below has: Exception in

3条回答
  •  不要未来只要你来
    2021-01-27 03:49

    The Exception is due to two read operation for getting one number, For Example take input as

    1

    2

    3

    END

    Debug:

    while loop condition input.nextLine() will fetch 1 then input.nextInt() will fetch 2 while loop condition input.nextLine() will fetch 3 then input.nextInt() will fetch END --> This will throw InputMismatchException

    Hope the bellow code will work, except the part that Any non int input will break the loop

    public static int scanaverage()
    {
    System.out.println("Enter any number, type 'END' to exit");
    Scanner input = new Scanner(System.in);
    int total=0; 
    int count = 0;
    
    while (input.hasNextInt()))
    {
    total += input.nextInt();
    count += 1;
    }
    return total / count;
    }
    

提交回复
热议问题