Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
132 views
in Technique[技术] by (71.8m points)

java - 用Java对数组排序(Sort an array in Java)

I'm trying to make a program that consists of an array of 10 integers which all has a random value, so far so good.

(我正在尝试制作一个包含10个整数的数组的程序,到目前为止,它们都具有随机值。)

However, now I need to sort them in order from lowest to highest value and then print it onto the screen, how would I go about doing so?

(但是,现在我需要按从最低到最高的顺序对它们进行排序,然后将其打印到屏幕上,我该怎么做?)

(Sorry for having so much code for a program that small, I ain't that good with loops, just started working with Java)

((对一个程序这么小的代码感到抱歉,我对循环不好,只是开始使用Java))

public static void main(String args[])
{
    int [] array = new int[10];

    array[0] = ((int)(Math.random()*100+1));
    array[1] = ((int)(Math.random()*100+1));
    array[2] = ((int)(Math.random()*100+1));
    array[3] = ((int)(Math.random()*100+1));
    array[4] = ((int)(Math.random()*100+1));
    array[5] = ((int)(Math.random()*100+1));
    array[6] = ((int)(Math.random()*100+1));
    array[7] = ((int)(Math.random()*100+1));
    array[8] = ((int)(Math.random()*100+1));
    array[9] = ((int)(Math.random()*100+1));

    System.out.println(array[0] +" " + array[1] +" " + array[2] +" " + array[3]
    +" " + array[4] +" " + array[5]+" " + array[6]+" " + array[7]+" " 
    + array[8]+" " + array[9] );        

}
  ask by Lukas translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Loops are also very useful to learn about, esp When using arrays,

(循环对于学习也非常有用,尤其是在使用数组时,)

int[] array = new int[10];
Random rand = new Random();
for (int i = 0; i < array.length; i++)
    array[i] = rand.nextInt(100) + 1;
Arrays.sort(array);
System.out.println(Arrays.toString(array));
// in reverse order
for (int i = array.length - 1; i >= 0; i--)
    System.out.print(array[i] + " ");
System.out.println();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...