为什么我的java数组不允许每个值的用户输入?

shi*_*eth 0 java arrays java.util.scanner

代码应该要求每个数组的三个输入:(ID,然后是Name,然后是Major).

ID工作完美,但是当它命名时,它打印出来:

请输入学生姓名:请输入学生姓名:

并且只允许该行的一个输入.然后它进入Major并再次正常工作.所以我最终得到3个ID,2个名字和3个专业.

这是我的代码:

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Chr*_*ian 5

会发生什么是nextLong()不消耗新行字符\n(按下时输入Intro).因此,在继续使用逻辑之前,您必须使用它:

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();
}
Run Code Online (Sandbox Code Playgroud)

注意:您可以阅读我之前写的这篇文章:[Java] nextInt()之前使用nextLine()