无法在数组中从最小到最大排序数字

时间:2013-04-19 22:19:30

标签: java arrays

这是我在这里的第一篇帖子,所以我不确定我是否正确发布了这个帖子。但我需要帮助尝试将状态的数量从最小到最大来自单独的文件。输出的所有程序都是按字母顺序排列的状态。该文件设置如下。

预期输入:

Alabama,4779736
Alaska,710231
Arizona,6392017  

尝试排序的类:

public class Inorder {

    /**
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        PrintWriter prw = new PrintWriter("outfile.txt");
        File f = new File("census2010.txt");
        if (!f.exists()) {
            System.out.println("f does not exist ");
        }
        Scanner infile = new Scanner(f);
        infile.useDelimiter("[\t|,|\n|\r]+");
        final int MAX = 50;
        int[] myarray = new int[MAX];
        String[] statearray = new String[MAX];
        int fillsize;

        fillsize = fillarray(myarray, statearray, infile);

        printarray(myarray, fillsize, prw);
        sortarray(myarray, statearray, fillsize);

    }

    public static int fillarray(int[] num, String[] states, Scanner infile) {

        int retcnt = 0;
        for (int count = 0; count < 50; count++) {

            int pop;
            String state;
            state = infile.next();
            pop = infile.nextInt();
            System.out.println(state + " " + pop + " ");
            states[retcnt] = state;
            num[retcnt] = pop;
            retcnt++;

        }
        return (retcnt);

    }

    public static void printarray(int[] num, int fillsize, PrintWriter prw) {
        for (int counts = 0; counts < fillsize; counts++) {
            System.out.println("For the position [" + counts
                    + "] the value is " + num[counts]);
            prw.println("For the position [" + counts + "] the value is "
                    + num[counts]);
        }
        return;
    }

    public static void sortarray(int[] poparray, String[] statearray,
            int fillsize) {

        for (int fill = 0; fill < fillsize - 1; fill = fill + 1) {

            for (int compare = fill + 1; compare < fillsize; compare++) {

                if (poparray[compare] < poparray[fill]) {
                    int poptemp = poparray[fill];
                    poparray[fill] = poparray[compare];
                    poparray[compare] = poptemp;
                    // do I need something here?
                    String statetemp = statearray[fill];
                    statearray[fill] = statearray[compare];
                    statearray[compare] = statetemp;

                }
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您的程序已经按照人口的升序对数组进行排序。

你只是没有看到它。

在您的主页中,您打印数组然后排序:

printarray (myarray, fillsize, prw);
sortarray(myarray, statearray, fillsize);

相反,尝试排序,然后才打印:

sortarray(myarray, statearray, fillsize);
printarray (myarray, fillsize, prw);

你会看到你的程序是正确的。

提示: 您可以使用System.out.println(Arrays.toString(myarray));轻松打印数组。