Lonely Twinky
Lonely Twinky

Reputation: 465

Reading certain integers from a text file into a Array List

I have to read two sets of integers in a text file. One is the number of credits that a student can have and then the next integer is a letter grade on a test. I can read the integers into an ArrayList, but the issue is that I want to read first the amount of credit they have, then choose which ArrayList to add them to, under a certain amount of credit or over a certain amount. I don't want to add the amount of credits up, just the grade they received. I have 25 lines of integers in the text file, first is the amount of credit, then a space, and then the grade. I only need to record the grade, not the credit amount. Here is what my code looks like so far:

public static void main(String[] args) throws FileNotFoundException 
{
    try
    {
        ArrayList <Integer> over15credits = new ArrayList<>();
        ArrayList <Integer> under15credits = new ArrayList<>();
        FileReader myReader = new FileReader("geomClass.txt");
        Scanner fileIn = new Scanner(myReader);

        while(fileIn.hasNextInt())
        {
            if(fileIn.nextInt() >= 15)
            {
                over15credits.add(fileIn.nextInt());

            }
            else
            {
                under15credits.add(fileIn.nextInt());
            }
            System.out.println(over15credits);
            System.out.println(under15credits);
        }
    }
    catch(FileNotFoundException e)
    {
        System.out.println("!!FILE NOT FOUND!!");
    }
}

Upvotes: 1

Views: 365

Answers (1)

Peter Lawrey
Peter Lawrey

Reputation: 533530

When you perform fileIn.nextInt() it reads and consumes the number so that when you call fileIn.nextInt() again it will read the number after that.

Most likely you meant to use a variable so that you can use the number you just read.

    int num = fileIn.nextInt();
    if (num >= 15)
        over15credits.add(num);
    else
        under15credits.add(num);

You want to use the same number you just read not another number.

FYI you can also write it like this.

    int num = fileIn.nextInt();
    (num >= 15 ? over15credits : under15credits).add(num);

Upvotes: 1

Related Questions