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

时间:2015-03-02 17:02:55

标签: 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();
        }
    }
}

2 个答案:

答案 0 :(得分:5)

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

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

注意:您可以阅读我刚才写的这篇文章:[Java] Using nextInt() before nextLine()

答案 1 :(得分:0)

而不是使用inReader.nextLine() 使用inReader.next()进行字符串输入。