2014-12-30 159 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