简体   繁体   中英

Java Scanner not accepting integer input before string

    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?

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()) .

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM