java - Sorting multiple arrays within a file. Putting states population in order -
**this first post don't know if did right. have read file , put list in order smallest largest population. alabama , shows 1 time. think problem "for" statement not sure. "return" statement. file set this
alabama,4779736
alaska,7102313**
import java.io.file; import java.io.ioexception; import java.io.printwriter; import java.util.scanner; 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 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){ for( int count = 0; count < 50; count++){ int retcnt = 0; 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){ (int counts = 0; counts < fillsize ; counts++){ system.out.println("for position ["+counts+"] value " + num[counts]); prw.println("for position ["+counts+"] value " + num[counts]); } return; } public static void sortarray(int[] poparray, string[] statearray, int fillsize){ for( int fill = 0; fill < fillsize -1; fill = fill+1){ ( int compare = fill+1; compare < fillsize; compare++){ if( poparray[compare] < poparray[fill]){ int poptemp = poparray[fill]; poparray[fill] = poparray[compare]; poparray[compare] = poptemp; // need here? string statetemp = statearray[fill]; statearray[fill] = statearray[compare]; statearray[compare] = statetemp; } } } } }
it looks need move return statement outside of loop.
public static int fillarray (int[] num, string[] states, scanner infile){ for( int count = 0; count < 50; count++){ // ... } // finish *all* iterations of loop, *then* return return (retcnt); }
by having return
inside loop, execute first iteration , method returns (preventing other 49 iterations). correctly in printarray
method.
edit:
as mentioned, moving return statement outside of loop makes retcnt
no longer accessible. because declare retcnt
inside loop; if declare retcnt
before loop, have no problems.
int retcnt = 0; (//...) { //... } // variable retcnt accessible entire method scope, // instead of loop block return retcnt;
Comments
Post a Comment