0

我是 java 和数组列表的新手。我应该排序填充一个充满随机整数的数组,然后如果有一个运行(一行中相同数字的倍数),则在该运行周围放置()。所以如果随机列表是:

2 3 4 5 5 5 5 6 7 7 9

2 3 4 (5 5 5 5) 6 (7 7) 9

这是我到目前为止所拥有的:

import java.util.*;

class Run {
  public static void main (String [] args){

    Scanner m = new Scanner(System.in);

    System.out.print("Enter length wanted: ");
    int len = m.nextInt();

    System.out.print("Enter max number wanted: ");
    int max = m.nextInt();
    max = max -1;

   int[] x = new int[len]; 
   ArrayList<String> y = new ArrayList<String>();

   //Filling x with random numbers
   for(int i = 0; i<len; i++){

    x[i] = ((int)(Math.random()*max)+1); 

   }

   System.out.println("Orginal Array: " + Arrays.toString(x));


   for(int i = 0; i<=len-1; i++){
     if(x[i] == x[i++]){ //I just don't know how I am exactly supposed to sort this

     }else{

     }

  }
   //Array List with ()
   System.out.println("Runs labeled Array: " + y);

  }
}
4

2 回答 2

0

用于Collections.sort(yourList)对 ArrayList 进行排序。

如果你不想使用 API 方法。

尝试 :

for(int i=0;i<list.size(); i++){
            for(int j=i+1; j<list.size(); j++){
                if(list.get(i)>list.get(j)){
                    temp = list.get(i);
                    list.set(i,list.get(j));
                    list.set(j, temp);
                }
            }
        }
于 2012-11-14T00:22:03.270 回答
0

您将需要一个字符串来显示最终输出。另外,不要走出阵列。尝试这样的事情:

x = Collections.sort(x);
String s = "";
boolean b;
for(int i = 0; i<=len-1; i++){
 if(x[i] == x[i+1]){
   s+=" ("+i+" ";
   b = true;
 }else{
   if(b == true){
      s+=i+") ";
      b = false;
   }
   s+=i + " ";
 }

}
于 2012-11-14T00:25:21.490 回答