用Java排序数组 [英] Sort an array in Java

查看:63
本文介绍了用Java排序数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个由10个整数组成的程序,这些整数都具有随机值,到目前为止一直很好。

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.

然而,现在我需要按照从最低到最高的顺序对它们进行排序,然后将其打印到屏幕上,我将如何进行排序?

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?

(很抱歉因为有这么多代码一个小的程序,我对循环不太好,刚开始使用Java)

(Sorry for having so much code for a program that small, I ain't that good with loops, just started working with 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] );        

}


推荐答案

循环是也非常有用,尤其是当使用数组时,

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();

这篇关于用Java排序数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆