2014-08-27 112 views
1

我具有以下;輸出被印刷兩次

import java.util.Scanner; 

public class Album{ 

    public static void main(String[] args){ 

     Scanner sc = new Scanner(System.in); 
     System.out.println("How many songs do your CD contain?"); 
     int songs = sc.nextInt(); 

     String[] songNames = new String[songs]; 

     for (int i = 0; i < songs; i++) { 
      System.out.println("Please enter song nr " + (i+1) + ": "); 
      songNames[i] = sc.nextLine(); 
      // What is wrong here? (See result for this line of code) 
      // It is working when I use "sc.next();" 
      // but then I can't type a song with 2 or more words. 
      // Takes every word for a new song name. 
     } 

     System.out.println(); 
     System.out.println("Your CD contains:"); 
     System.out.println("================="); 
     System.out.println(); 

     for (int i = 0; i < songNames.length; i++) { 
      System.out.println("Song nr " + (i+1) + ": " + songNames[i]); 
     } 
    } 
} 

我不能鍵入歌曲名稱NR 1,因爲它總是顯示前兩個在一起。

喜歡這一點,如果我3型:

How many songs do your CD contain? 
3 
Please enter song nr 1: 
Please enter song nr 2: 
+0

我編輯你的問題,給它一個更好的標題。當然,你的舊標題給人們一個挑戰,就是要做一些代碼檢測工作來找到你的代碼中的問題,並且它的目的很好,有5個答案,但是前面的_我的代碼有什麼問題?檢查我的評論行可能已經安裝了任意多的問題。 – ljgw 2014-08-27 11:33:41

回答

3

變化

int songs = sc.nextInt();

到:

int songs = Integer.parseInt(sc.nextLine().trim());

,它會正常工作。

您不應該混合使用nextIntnextLine

+0

謝謝你的回答! – Yonetmen 2014-08-27 11:33:42

1

添加sc.nextLine();int songs = sc.nextInt();

一旦你輸入一個數字,並使用使用sc.nextInt();掃描儀(如數字)讀它時,換行符字符將出現在輸入流中,當您執行sc.nextLine()時將會讀取該輸入流。因此,跳過(以上),你需要調用sc.nextLine()sc.nextInt();

+0

謝謝你的解釋! – Yonetmen 2014-08-27 11:34:38

0

sc.nextInt()之後添加一個sc.nextLine()並且您的代碼正常工作。

原因是在輸入歌曲的數字後結束行。

0

要麼使用nextIntnextLine,我會選擇nextLine

import java.util.Scanner; 

public class Album{ 

    public static void main(String[] args){ 

    Scanner sc = new Scanner(System.in); 
    System.out.println("How many songs do your CD contain?"); 
    int songs = Integer.parseInt(sc.nextLine()); // instead of nextInt() 

    String[] songNames = new String[songs]; 

    for (int i = 0; i < songs; i++) { 
     System.out.println("Please enter song nr " + (i+1) + ": "); 
     songNames[i] = sc.nextLine(); 
     // What is wrong here? (See result for this line of code) 
     // It is working when I use "sc.next();" 
     // but then I can't type a song with 2 or more words. 
     // Takes every word for a new song name. 
    } 

    System.out.println(); 
    System.out.println("Your CD contains:"); 
    System.out.println("================="); 
    System.out.println(); 

    for (int i = 0; i < songNames.length; i++) { 
     System.out.println("Song nr " + (i+1) + ": " + songNames[i]); 
    } 
    } 
} 
0

把sc.nextLine();之後int歌曲= sc.nextInt();