0

The code is supposed to ask for three inputs of each array: (ID, then Name, then Major).

The ID works perfectly, but then when it goes to name, it prints out:

Please enter the student's name: Please enter the student's name:

and only allows one input for that line. Then it goes onto Major and works correctly again. So i end up with 3 IDs, 2 names, and 3 majors.

Here is my code:

package STUDENT;

import java.util.Scanner;

public class StudentDisplayer {

    public static void main(String[] args) {

        long[]studentId = {11, 22, 33};
        String[] studentName = {"Value1", "Value2", "Value3"};
        String[] studentMajor = {"Value1", "Value2", "Value3"};
        Scanner inReader = new Scanner(System.in);


             /* ----------------------------------------------
            Print the information in the parallel arrays
            ---------------------------------------------- */

        for (int i = 0; i < studentId.length; i++ ){
            System.out.println("Please enter the student's id: ");
            studentId[i] = inReader.nextLong();
        }

        for (int i = 0; i < studentName.length; i++){
            System.out.println("Please enter the student's name: ");
            studentName[i] = inReader.nextLine();
        }

        for (int i = 0; i < studentMajor.length; i++){
            System.out.println("Please enter the student's major: ");
            studentMajor[i] = inReader.nextLine();
        }

        for (int i = 0; i < studentId.length; i++ )
        {
            System.out.print( studentId[i] + "\t");   
            System.out.print( studentName[i] + "\t");  
            System.out.print( studentMajor[i] + "\t");
            System.out.println();
        }
    }
}
mkobit
  • 34,772
  • 9
  • 135
  • 134
shibboleth
  • 21
  • 4

2 Answers2

5

What happens is that nextLong() doesn't consume the new-line character \n (which is entered when you press Intro). So, you will have to consume it before you continue with your logic:

for (int i = 0; i < studentId.length; i++ ){
    System.out.println("Please enter the student's id: ");
    studentId[i] = inReader.nextLong();
}

inReader.nextLine(); // ADD THIS

for (int i = 0; i < studentName.length; i++){
    System.out.println("Please enter the student's name: ");
    studentName[i] = inReader.nextLine();
}

Note: You can read this article, which I wrote some time ago: [Java] Using nextInt() before nextLine()

Christian
  • 31,246
  • 6
  • 45
  • 67
0

Instead of using inReader.nextLine() use inReader.next() for String inputs.

Piyush Vishwakarma
  • 1,661
  • 3
  • 12
  • 20