【问题标题】:Sorting Arrays from 2010 Census in Java用 Java 对 2010 年人口普查中的数组进行排序
【发布时间】:2013-04-12 04:22:09
【问题描述】:

我完成了这个程序,但出了点问题。我的意思是它没有打印出它需要的东西。它应该从人口普查中获取人口以及州名,然后从最小到最大的州对其进行排序。当我运行该项目时,它会打印出阿拉巴马州及其人口 50 次,而不是从最小人口到最大人口的所有州,我不确定该怎么做,我真的需要一些帮助,拜托。人口普查的一个例子如下...... 这些中的每一个都将在不同的行上:

阿拉巴马州,4779736
阿拉斯加,710231
亚利桑那州,6392017

这是程序:

    public static void main(String[] args) throws IOException {
    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) throws FileNotFoundException{

    int retcnt = 0;
    int pop;
    String state;
    state = infile.next();
    pop = infile.nextInt();
    for( int count = 0; count < 50; count++){
        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;
            }
        }
    }
}

我认为我的问题出在排序数组中,但我做错了什么?

【问题讨论】:

  • 您正在打印填充数组(应称为填充数组)中的状态和人口。但是,您永远不会在该循环中更新 state 变量。所以它总是会在那个循环中打印阿拉巴马州。不过,不确定这是否是您关心的输出。
  • 使用Collections#sort() 而不是sortarray()

标签: java arrays sorting methods


【解决方案1】:

fillarray 方法中,您只能从 Scanner 读取一次。您需要将从 Scanner 读取的代码放在 for 循环中,以便它在每次循环迭代时读取一行数据。

【讨论】:

    猜你喜欢
    • 2019-02-23
    • 1970-01-01
    • 1970-01-01
    • 2012-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多