Search code examples
javaarraysfor-loopfilestream

Loop Array Making Me Loopy


So i have been at this same example problem for a week now. I know that it may seem easy, but i am finding that the more i look at it or alter it, the more confused i get. I feel like i am making this a lot more difficult than it needs to be. The array that i loaded displays correctly in the Try-Catch section, but i need to display it in its own method, which i call listOfAges(). What would this look like? Any responses are appreciated, please help.

class ArrayDemo {
public static void main(String[] args) {

    int[] anArray;
    int ageCount = 0;
    int age;
    String filename = "ageData.dat";

    anArray = new int[50];
    /* The file has 50 numbers which represent an employee's age */
    try {
        Scanner infile = new Scanner(new FileInputStream(filename));

        while (infile.hasNext()) {

            age = infile.nextInt();
            ageCount += 1;

            System.out.println(ageCount + ". " + age + "\n");
            /* 
             * When i run just this, the output is correct...
             * 
             * But i don't want the output here, i just want to gather 
             * the information from the file and place it at the bottom inside
             *  the method displayAges().*/

        }

        infile.close();

    } catch (IOException ex) {
        ageCount = -1;
        ex.printStackTrace();
    }


    public void listOfAges() {
        System.out.print("  I want to display the data gathered from ageData.dat in this method  ");
        System.out.print("  Also, i receive this error message when i try: 'Illegal modifier for parameter listOfAges; only final is permitted'  ")
    }  


}
}

Solution

  • First, you have to store your values in your array:

    while (infile.hasNext()) {
        age = infile.nextInt();
        anArray[ageCount] = age;
        ageCount += 1;
    }
    

    Your next problem is that you defined your listOfAges() method inside your main() method. The definition must be outside. You also need to pass your array as an argument to your method so that you can iterate over the array values to print them:

    public void listOfAges(int[] ages) {
        // use a loop here to print all your array contents
    }