2013-04-26 95 views
0

所以程序應該允許用戶輸入10個分數並在下一行按升序打印這些分數。出於某種原因,它允許我輸入分數,但下面的行只填充0而不是按升序對輸入進行排序。我不確定爲什麼,但任何輸入都會有所幫助。打印0而不是鍵盤輸入

public static void main(String[] args) { 
    Scanner keyboard = new Scanner(System.in); 

    System.out 
      .println("Enter up to 35 scores between 0 and 100, -1 to stop:"); 

    int[] score = new int[35]; 
    int count = 0; 
    int sum = 0; 
    String scores = ""; 

    for (int i = 0; i < score.length; i++) { 
     score[i] = keyboard.nextInt(); 
     if (score[i] >= 0) { 

      scores = scores + score[i] + "  "; 
      count++; 
      sum = sum + score[i]; 
     } else 
      i = score.length + 1; 

    } 

    for (int i = 1; i < score.length; i++) { 
     int x; 
     int temp; 

     x = score[i]; 
     temp = score[i]; 
     for (x = i - 1; x >= 0 && score[x] > temp; x--) { 
      score[x + 1] = score[x]; 
     } 
     score[x + 1] = temp; 
    } 

    System.out.printf("The %d scores you entered are: \n%s", count, scores); 
    System.out.println(); 
    System.out.printf("The %d scored sorted in nondecreasing order are:\n", 
      count); 
    int k=1; 
    for (k=1; k <= count; k++) { 
     if (k % 11 == 0) { 
      System.out.println(); 
     } else { 
      System.out.printf("%5d", score[k]); 
     } 
    } 

    for (int i = 1; i <= count; i++) { 
     if (i % 11 == 0) { 
      System.out.println(); 
     } else { 
      System.out.printf("%5d", score[i]); 
     } 

     for (int j = 1; j < count; j++) { 
      if (Integer.compare(score[i], score[j]) < 0) { 
       int temp = score[i]; 
       score[i] = score[j]; 
       score[j] = temp; 
      } 
     } 
    } 
+2

一篇關於Eclipse中Java調試的文章:http://www.vogella.com/articles/EclipseDebugging/article.html。 – valentinas 2013-04-26 01:23:13

回答

1

我同意關於學習調試的評論。您編寫代碼的方式很明顯,您是初學者,所以這裏是幫助您的答案。要回答你的問題,你的程序中有幾個邏輯錯誤。

您可以簡單地使用break來退出第一個for循環。所以在else語句中只需寫入break;而不是i = score.length + 1;

接下來......錯誤在於你正在排序整個數組...然而,因爲在輸入-1之前你可能只輸入了5或6個元素,所以你的前5或6個元素將具有值和所有其他值得分數組爲0.如果你排序整個數組,你顯然會把0放在前面,將實際得分放到數組的後面。這是你的問題的答案。從i = 0到i <計數。這將解決你的一些問題,但你有更多的問題。

還有其他幾個問題。我希望你能夠調試和發現。

+0

使用ArrayList與使用數組相比是一個更好的主意,因此大小將成爲輸入分數的實際數量,並且不需要將分數上限設置爲35. – gparyani 2013-04-26 02:44:13

+0

是的,如果我編寫該程序,那是我會用的。 – Buddha 2013-04-26 03:37:12