我完成了這個程序,出了點問題。我的意思是不打印出需要的東西。它應該把普查中的人口和國家名稱一起,並將其從最小狀態分類到最大狀態。當我運行這個項目時,它會打印出阿拉巴馬州和它的人口50次,而不是所有的州從最小到最大的人口,我不確定要做什麼,我真的可以使用一些幫助。普查的一個例子是如下... 每個部分都會在不同的行:2010年人口普查排序陣列
阿拉巴馬州,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;
}
}
}
}
我想我的問題是何許陣中,但我究竟做錯了什麼?
您正在打印fillarray中的狀態和人口(應該稱爲fillArray)。但是,你永遠不會更新那個循環中的'state'變量。所以它總是會在這個循環中打印阿拉巴馬州。不過,不知道這是否是你關心的輸出。 – Marvo
使用['Collections#sort()'](http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Collections.html#sort%28java.util.List,%20java .util.Comparator%29)而不是'sortarray()'。 – m0skit0