Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8285912

(scanner) Buffer isn't cleared when exception occur in try/catch block

    XMLWordPrintable

Details

    • generic
    • generic

    Description

      ADDITIONAL SYSTEM INFORMATION :
      Ubuntu 20.04
      openJDK 11.0.14.1

      A DESCRIPTION OF THE PROBLEM :
        import java.util.Scanner;
        public class Main {
             public static void main(String[] args) {
                 Scanner sc = new Scanner(System.in);
                 String inputStr = null;
                 int [] scoreASM = new int[2];
                 int j=1;
                 int asmNumber = 3;
                 while (asmNumber > 0){
                    while (true) {
                        try {
                            System.out.print("Assignment " + j + " score and max: ");
                            for (int i = 0; i < 2; i++) {
                                inputStr = sc.next();
                                scoreASM[i] = Integer.parseInt(inputStr);
                            }
                            break;
                        } catch (NumberFormatException e) {
                            System.out.println("Invalid input. Please enter a Integer number");
                        }
                    }
                    j ++;
                    asmNumber --;
                }
            }
       }
      -----------------------------------------------------
      Assignment 1 score and max: wrong wrong2
      Invalid input. Please enter a Integer number
      Assignment 1 score and max: Invalid input. Please enter a Integer number
      Assignment 1 score and max: wrong 45
      Invalid input. Please enter a Integer number
      Assignment 1 score and max: 78 wrong2
      Assignment 2 score and max: Invalid input. Please enter a Integer number <==== should be re-enter for Assignment 1, because there is input is invalid.
      Assignment 2 score and max:


      Attachments

        Activity

          People

            smarks Stuart Marks
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved: