1

So I have this code that I am working on that is supposed to calculate a user GPA depending on the input and I have made a method to ask the user a series of questions and my goal is to get a output like this

Course 1:

Class: user input

Is AP: user input

Grade: user input

Course 2:

Class: user input

Is AP: user input

Grade: user input

Course 3:

Class: user input

Is AP: user input

Grade: user input

Course 4:

Class: user input

Is AP: user input

Grade: user input

to do this I have made this code

public static void askQuestions() 
  {
    Scanner input = new Scanner(System.in);
    for (int i = 1; i < 5; i++) 
    {
    System.out.println("Course " + i + ":");
    System.out.print("    Class:  ");
    String courseName = input.nextLine();
    System.out.print("    is AP:  ");
    String answer = input.nextLine();
    System.out.print("    Grade:  ");
    int Grade = input.nextInt();
    }
  }

but my result is this

Course 1:

Class: user input

Is AP: user input

Grade: user input

Course 2:

Class: Is AP: user input

Grade: user input

Course 3:

Class: Is AP: user input

Grade: user input

Course 4:

Class: Is AP: user input

Grade: user input

like the first loop is fine but the rest of the loop is not. what am I doing wrong???

1 Answers1

0

input.nextInt(); reads only integer, and new line symbol(\n) still remains, so subsequent nextLine reada this \n, \n is enter press

It's looks like this

Class: A\n(reads all)

Is AP: something \n(reads all)

Grade: 23\n(reads 23 only)

Class: \n(from prev input)

you should write like this Integer.parseInt(input.nextLine())

Shevtsov
  • 140
  • 9