Java扫描程序输出数组值并在排序方法后输出

时间:2016-04-12 01:13:15

标签: java arrays sorting

我还有其他代码可以输出min,max和average等值。我没有看到如何在用户通过扫描仪输入的排序数组中输出值。

import java.util.Scanner;

public class Arrayassignment {

    public static void main(String[] args) {
        Scanner keyboard=new Scanner(System.in);
        System.out.println("Enter an integer for array size.");
        int number= keyboard.nextInt();
        int array[]=new int[number];
        System.out.println("Array size " + number + " initiated.\n");
        System.out.println("Now enter the array integers.");
        for (int index = 0; index < number; index++)
        {  
            array[index]=keyboard.nextInt();
        }
        keyboard.close();

        System.out.println ( "Sorting " );
          sort(array);
    }

    public static void sort(int[] arg) {
        int arrange;
        for (int i = 0; i < arg.length - 1; i++)
            for (int j = i + 1; j < arg.length; j++) {
                if (arg[i] > arg[j]) {
                    arrange = arg[i];
                    arg[i] = arg[j];
                    arg[j] = arrange;
                    System.out.println( arrange);
                }
            }
        }        
    }
}

1 个答案:

答案 0 :(得分:0)

问题有点不清楚。我想你想要的是输出和打印排序的数组。

import java.util.Scanner;
import java.util.Arrays;

public class Arrayassignment {

    public static void main(String[] args) {
        Scanner keyboard=new Scanner(System.in);
        System.out.println("Enter an intiger for array size.");
        int number= keyboard.nextInt();
        int array[]=new int[number];
        System.out.println("Array size " + number + " initiated.\n");
        System.out.println("Now enter the array intigers.");
        for (int index = 0; index < number; index++)
        {  
            array[index]=keyboard.nextInt();
        }
        keyboard.close();

        System.out.println ( "Sorting " );
        //call the sort mthod and get the returned sorted array
        int[] sortedArray=sort(array);

        //printing the sorted array
        System.out.println(Arrays.toString(sortedArray));

    }

    public static int[] sort(int[] arg) {
        int arrange;
        for (int i = 0; i < arg.length - 1; i++){
            for (int j = i + 1; j < arg.length; j++) {
                if (arg[i] > arg[j]) {
                    arrange = arg[i];
                    arg[i] = arg[j];
                    arg[j] = arrange;
                }
            }
        }
        //return the sorted array
        return arg;        
    }
}