2014-12-30 163 views
2

我對此很新,而且我一直在做我的任務,所以任何人都可以請幫忙。我在排序輸出時遇到問題。這裏是代碼。如何對數據進行排序

  import java.util.Scanner; 

      public class CJPSA5 { 
       public static void main(String args[]){ 
        Scanner in= new Scanner(System.in); 
        int num; 
        int m; 
        int r; 
        System.out.print("Please Enter your Number: "); 
        num = in.nextInt(); 

        if (num <= 0) { 
         System.out.println("Not Accepted!"); 
        } else { 
         System.out.println("The Factor of "+ num + " " + "are:"); 
         for (m = 1; m <= num; m++) { 
          if (num % m == 0) { 
           System.out.print(m + "\t"); 
           System.out.print(j + "\t"); 
          } 
         } 
        } 
       } 
      } 
     } 
     System.out.println(); 
     System.out.println("Thank You!"); 
    } 
} 

預期的輸出是這樣的。

Please Enter your Number: 24 
The Factor of 24 are: 
1 -1 2 -2 3 -3 4 -4 6 -6 8 -8 12 -12 24 -24 

現在我想成爲輸出類似

1 2 3 4 6 8 12 24 -1 -2 -3 -4 -6 -8 -12 -24 

進行排序我真的希望有人能幫助我,對不起,我錯了語法。

+2

你的問題的代碼是不是你正在使用的代碼。爲什麼不? – immibis

+1

您的代碼將不會編譯 – tapananand

+0

您正在打印出一個j變量,但是在您的代碼中沒有。嘗試保存ArrayList的答案,然後對它們進行排序,而不是打印。 –

回答

1

首先你的代碼有很多編譯錯誤。不需要對數組進行排序。只將積極因素存儲在數組中。

您的數組將按照您運行循環的方式自行排序。只需循環遍歷每個數字的數組print negative以打印負面因素。

例如: 輸入:14

陣列具有1 2 7 14以及這些值已經由打印現在。

然後通過它循環和打印:-1 -2 -7 -14

+0

做了你所說的......但我的索引超出了界限異常 –

+0

你是如何循環陣列的? – tapananand

+0

如果您有解決方案,請點擊答案左側的勾號將解決方案標記爲解決方案。 – tapananand

1

您可以將值存儲在java中的數組或數組列表中。並使用它的排序方法。

你可以像Tapan Anand所建議的那樣,不用排序。

+1

沒有必要排序。 – tapananand

+0

編輯答案。謝謝你指出。 –

1

首先收集您的解決方案的列表:

在頂部:

List<Integer> factors = new ArrayList<Integer>(); 

然後在循環:

if (num % m == 0) 
    factors.add(m); 

然後在循環之後:

Collections.sort(factors); 

然後打印:

for (int factor : factors) { 
    System.out.println(factor + "\t"); /// or whatever