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

前端 未结 3 406
闹比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:54

    You can simply add a try catch block as follows.

    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.nextLine().equals("END")))
      {
       try{
        total += input.nextInt();
        count += 1;
        }catch(InputMismatchException e){
    
        }
      }
      return total / count;
    }
    

    I haven't test it.

提交回复
热议问题