2015-05-09 28 views
1

我想創建一個程序,允許我輸入5個不同人的姓名,年齡和出生年份。但是,在我輸入for循環中的第一個名稱後,我遇到了無法輸入其他名稱的問題。這裏是我的代碼:當我運行它爲什麼我不能在for循環中第一次輸入另一個字符串?

public static void main(String[] args) { 

    String[] names = new String[5]; 
    int[] s = new int[5]; 
    Scanner keyboard = new Scanner (System.in); 

    for (int i = 0; i < 5; i++) { 
     System.out.print("Name: "); 
     names[i] = keyboard.nextLine(); 
     System.out.print("Age: "); 
     s[i] = keyboard.nextInt(); 
     System.out.print("Year: "); 
     s[i] = keyboard.nextInt(); 
    } 
} 

程序工作正常,但它不會讓我我進入後先進入其他4名。這是我得到的輸出:

sample output

+3

http://stackoverflow.com/questions/13102045/skipping-nextline-after-use-next-nextint-or-other-nextfoo-methods – Reimeus

回答

3

請注意:

String java.util.Scanner.next() - Returns:the next token 
String java.util.Scanner.nextLine() - Returns:the line that was skipped 

更改代碼[做,而初始行]如下:

names[i] = keyboard.next(); 
+0

這應該工作:) –

+0

BProgram - 你驗證過嗎?這必須解決您的問題。 – Rajesh

+0

@Rajesh對不起,回覆晚了。是的,這已經解決了我的問題,我的程序工作正常。謝謝您的幫助。 –

2

乘坐look-我修復了你的代碼 - 添加了「keyboard.nextLine();」最後。

public static void main(String[] args) { 


     String[] names = new String[5]; 
     int[] s = new int[5]; 
     Scanner keyboard = new Scanner (System.in); 

     for (int i = 0; i < 5; i++) { 

      System.out.print("Name: "); 
      names[i] = keyboard.nextLine(); 
      System.out.print("Age: "); 
      s[i] = keyboard.nextInt(); 
      System.out.print("Year: "); 
      s[i] = keyboard.nextInt(); 
      keyboard.nextLine(); 
     } 
    } 

你需要添加它的原因是,「nextInt()」將只讀取您輸入的內容,而不是行的其餘部分。該行的剩餘部分將被「names [i] = keyboard.nextLine();」自動。

通過在最後放置另一個「keyboard.nextLine()」,我跳過了該行的剩餘部分,然後「命名[i] = keyboard.nextLine();」從一個新的行讀取輸入。

在Java中每個初學者遇到這個問題遲早:)

相關問題