1

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!!"); } } 
2
  • 1
    Does it work? If not, what problem/error do you have? Commented Dec 11, 2015 at 23:52
  • It is just adding all of the integers together in the arrays(including the credits), when I print out both ArrayLists, it will not crash but send around 20 lines of Arrays instead of just one line of an Array. But, if I only print out 1 ArrayList, the program will print it out and then crash. Other than that, the program will run. Commented Dec 12, 2015 at 0:19

1 Answer 1

1

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); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.