Reading text files, for in while vs while in for (java)

This is a very easy code sample of an exercise for school. I got it to work, but I don’t understand why my first idea didn’t work. My first idea was the while loop in the double for loop (see comments /* */). If I used those loops it gave me an array back that was filled with zeros (there is a file integer.txt with random numbers in the same direction, that’s not the problem).

Has it something to do with sc.hasNextInt()? I really don’t understand why it works in this way and not the other.

Thanks for explaining in advance.

public static void main(String[] args) throws IOException {
    String filename = "integer.txt";
    FileReader fr = new FileReader(filename);
    Scanner sc = new Scanner(fr);

    int[][] getallen = new int[2][5];

    /*for(int i = 0; i < 2; i++){
        for(int j = 0; j < 5; j++){
            while(sc.hasNextInt()){
                getallen[i][j] = sc.nextInt();
            }
        }
    }*/



    while(sc.hasNextInt()){
        for(int i = 0; i < 2; i++){
            for(int j = 0; j < 5; j++){
                getallen[i][j] = sc.nextInt();
            }
        }
    }

    for(int i = 0; i < 2; i++){
        for(int j = 0; j < 5; j++){
            System.out.print(getallen[i][j] + " ");
        }
        System.out.println();
    }


    System.out.println("Ok.");
    sc.close();
 }

Answer

Inside your while loop i and j never move on, so within your while loop you were constantly over-writing the same positions inside getallen.

Just trace through what the code does and it should be obvious. i and j are 0. It then loops through pulling everything from the scanner and setting it into getallen[0][0]. It’s then exhausted the scanner so it moves on with 0,0 containing the last scanner value. For every other step (unless something new comes into the scanner) hasNextInt() returns false so it never even executes and getallen[i][j] is not modified, which means it keeps its default value of 0.

Leave a Reply

Your email address will not be published. Required fields are marked *