2015-03-02 72 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()用於字符串輸入。

相關問題