2015-03-02 71 views
0

代码应该要求每个数组的三个输入:(ID,然后名称,然后是主要)。为什么我的java数组不允许用户输入每个值?

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

回答

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

注:您可以阅读这篇文章,我写了前段时间:使用inReader.nextLine() 使用[Java] Using nextInt() before nextLine()

0

代替inReader.next()用于字符串输入。

相关问题