Sort an array in Java

后端 未结 17 950
傲寒
傲寒 2020-11-22 04:53

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 l

17条回答
  •  清酒与你
    2020-11-22 05:36

    I was lazy and added the loops

    import java.util.Arrays;
    
    
    public class Sort {
        public static void main(String args[])
        {
            int [] array = new int[10];
            for ( int i = 0 ; i < array.length ; i++ ) {
                array[i] = ((int)(Math.random()*100+1));
            }
            Arrays.sort( array );
            for ( int i = 0 ; i < array.length ; i++ ) {
                System.out.println(array[i]);
            }
        }
    }
    

    Your array has a length of 10. You need one variable (i) which takes the values from 0to 9.

    for ( int i = 0  ; i < array.length ;   i++ ) 
           ^               ^                   ^
           |               |                   ------  increment ( i = i + 1 )
           |               |
           |               +-------------------------- repeat as long i < 10
           +------------------------------------------ start value of i
    
    
    Arrays.sort( array );
    

    Is a library methods that sorts arrays.

提交回复
热议问题