1
    public static void main(String[] args) {

       Student[] test = new Student[7];

      for (int i = 0; i < 7; i++) {
        test[i] = new Student();

        Scanner kb = new Scanner(System.in);
        System.out.println("What is the Students ID number?: ");
        test[i].setStudentId(kb.nextInt());
        System.out.println("What is the Students name?: ");
        test[i].setStudentName(kb.nextLine());
      }

    }

In the above program when I try to take integer input at first it skips the String input, but in the same program if i keep the string input at first it works fine. What might be the reason behind this?

        Scanner kb = new Scanner(System.in);

        System.out.println("What is the Students name?: ");
        test[i].setStudentName(kb.nextLine());
        System.out.println("What is the Students ID number?: ");
        test[i].setStudentId(kb.nextInt());

the output of the program would be

What is the Students ID number?: 1

What is the Students name?: //it wouldn't let me enter string here

What is the Students ID number?:

But when I take input for Integer above the string It works fine. What might be the reason?

2 Answers 2

4

The call to nextInt() only reads the integer, the line separator (\n) is left in the buffer, so the subsequent call to nextLine() only reads until the line separator already there. The solution is to use nextLine() for the ID as well and then parse it to an integer using Integer.parseInt(kb.nextLine()).

Sign up to request clarification or add additional context in comments.

Comments

1

After you call nextInt(), the scanner has advanced past the integer but not past the end of the line on which the integer was entered. When you try to read the ID string, it reads the rest of the line (which is blank) without waiting for further input.

To fix this, simply add a call to nextLine() after calling nextInt().

System.out.println("What is the Students ID number?: ");
test[i].setStudentId(kb.nextInt());
kb.nextLine(); // eat the line terminator
System.out.println("What is the Students name?: ");
test[i].setStudentName(kb.nextLine());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.