我完成了这个程序,但出了点问题。我的意思是它没有打印出它需要的东西。它应该从人口普查中获取人口以及州名,然后从最小到最大的州对其进行排序。当我运行该项目时,它会打印出阿拉巴马州及其人口 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;
}
}
}
}
我认为我的问题出在排序数组中,但我做错了什么?