1

Hi I am writing java code that will take user input and place the user input into an ArrayList but I want the user to be able to enter Q when they have input all the data. But when I input q on certain instances I am getting the wrong output.

public void enterScores() 
{
    System.out.println("Enter the scores of the student, press Q to finish");
    for (int i = 0; i < SCORES_SIZE; i++)
    {
        exitLoop = userInput.next();
        if (exitLoop.equalsIgnoreCase("Q"))
        {
            break;
        }
        scores.add(i, userInput.nextInt());
    }
    System.out.println("___________");
    for (int i = 0; i < scores.size(); i++)
        System.out.println(scores.get(i)); //Prints out the arraylist of scores entered
    System.out.println("_____");
    System.out.println(scores.size()); //prints out the size of the arraylist but is wrong
}

The following code after the for loop was only so I could make sure it was running properly but unfortunately it is not. It seems as if it is only reading some of the numbers into the ArrayList So the input I am getting is:

   Enter the scores of the student, press Q to finish
12
13
14
145
14
13
q
___________
13
145
13
_____
3

So when I enter q (to quit the loop) in an odd position, the program will exit the loop but the only numbers that are read into the ArrayList are the numbers in the even positions. And when i enter q in an even position I get the following error:

Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at Chapter_7.GradeBook.enterScores(GradeBook.java:36)
    at Chapter_7.GradeBookTester.main(GradeBookTester.java:12)
user2152012
  • 131
  • 1
  • 2
  • 12
  • Possible duplicate of [Take a char input from the Scanner](https://stackoverflow.com/questions/13942701/take-a-char-input-from-the-scanner) – Steephen Dec 09 '17 at 15:03
  • use `next()` so that you can take a `String` input. then extract the first char out of it. `nextInt()` would give an exception because the input parsed is not an integer when `Q` is the input. – Anindya Dutta Dec 09 '17 at 15:15

1 Answers1

1

Try this one:

public void enterScores() {
    Scanner userInput = new Scanner(System.in);
    System.out.println("Enter the scores of the student, press Q to finish");
    for (int i = 0; i < SCORES_SIZE; i++) {
        String input = userInput.next();
        if ("Q".equals(input)) {
            break;
        }
        try {
            scores.add(i, Integer.parseInt(input));
        } catch (NumberFormatException e) {
            System.out.println("entered value can not be casted to integer");
        }
    }
}
Mostafa
  • 109
  • 1
  • 11