2012-09-23 82 views
1

我只在我的第二學期的java中,所以可能有一個非常簡單的解決方案來解決我的問題,但因爲這個原因,我一直在拉我的頭髮。以下代碼正在用於收集用戶輸入並將實例的信息存儲在數組中。Java家庭作業(使用for循環填充數組)

沒有機會爲專輯名稱輸入任何內容。輸出如下。

進入5首歌曲

標題:標題
作者:作者1
解釋:INT1
發行年份:2000
專輯:文件名://爲什麼不這樣收集的輸入和地點文件名:在下一行。

如果任何人都可以點我在正確的方向,我將不勝感激。我在下面列出了兩種方法,以防他們與我的問題有關。感謝您的任何幫助,您可以提供。

public static void main(String[] args){ 

    Scanner kybd = new Scanner(System.in); 

    Song[] songTest = new Song[5]; 

    System.out.println("Enter 5 songs\n"); 


    //TEST 
    for(Song x:songTest) 
    { 
     x = new Song(); 
     System.out.print("Title: "); 
     x.setTitle(kybd.nextLine()); 
     System.out.print("Author: "); 
     x.setAuthor(kybd.nextLine()); 
     System.out.print("Interpreter: "); 
     x.setInterpreter(kybd.nextLine()); 
     System.out.print("Year released: "); 
     x.setYearReleased(kybd.nextInt()); 
     System.out.print("Album: "); 
     x.setAlbum(kybd.nextLine()); //this doesn't allow for input. it prints "File name:" and skips the user input for an album name. Also, when I comment out Year released, the problem goes away. 
     System.out.print("File name: "); 
     x.setFileName(kybd.nextLine()); 
     System.out.print(x); 
     System.out.println(); 
    } 


public void setYearReleased(int y) 
{ 
    if (y>0 && y<2013) 
     this.yearReleased = y; 
    else 
    { 
     System.out.print ("This song is not that old"); 
     this.yearReleased = -5; 
    } 
} 

    public void setAlbum(String a) 
{ 
    this.album = a; 
} 
+1

我喜歡如何設置發佈年份到2014年的結果'這首歌曲不是那麼古老'打印在標準輸出上。 – sehe

回答

3

你需要做一個kybd.nextLine()kybd.nextInt()後,使下面的kybd.nextLine()不捕獲迫切要求nextInt()輸入時的換行使用。

+0

非常感謝您的幫助。我偶爾碰到一些非常令人沮喪的菜鳥錯誤。此外,我刪除了一首歌曲需要的限制<2013年。此外,還有一些建設性的批評。 –

2
x.setYearReleased(kybd.nextInt()); 

不與行字符的結尾做任何事情,將繼續上線讓你看到的行爲。快速修復可能是在此之後添加另一個ktbd.nextLine();以在下一個int之後跳過該行上的其他任何內容。

System.out.print("Year released: "); 
x.setYearReleased(kybd.nextInt()); 
kybd.nextLine() 
System.out.print("Album: "); 
x.setAlbum(kybd.nextLine());