-1

Basically, I am not using any of the Java API classes such as ArrayLists or LinkedLists, as I have created my own custom linked list class which in this case is named FoodList. I am trying to figure out a way to read each line from a file where each line is an object, and store it in FoodList.

I've looked at many examples of reading files online, but none of them were for a custom linked list.

package lab9;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;

public class Console {

    FoodList x = new FoodList();

    public Console(){
        this.x = new FoodList();
    }

    public void Display() {

        System.out.println("============================================================================");
        System.out.println("Name                Food Group          Calories            Daily percentage   ");
        System.out.println("============================================================================");

        File f = new File("food.txt");

        try {
            Scanner scan = new Scanner(f);  //What I tried to do to read in objects from file

            while(scan.hasNextLine()){
                String line = scan.nextLine();
                String[] details = new String[4];
                details = line.split(" ");
                String name = details[0];
                String group = details[1];
                int calories = Integer.parseInt(details[2]);
                double percentage = Double.parseDouble(details[3]);
                x.add(new Food(name, group, calories, percentage));
            }

            System.out.println(x);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            System.out.println("Not working");
        }
    }

}

The code below is also giving me an out of bounds exception at line 30. Should I try to read the objects differently or fix this?

NOTE: PLEASE do not mark this as a duplicate, I have already made my String[] details variable to hold more than 1 array.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
  • Why did you do this? The question does not solve my problem – Markusovic Aug 03 '19 at 21:23
  • I guess your file has an empty line at the end and that's causing the problem. After you read a line `scan.nextLine()` check if it contains anything (`line.length()>0`) before you try to split it. You can also try `System.out.println(line)` so you know which one is problematic. – Krystian G Aug 03 '19 at 21:49
  • Before asking questions like this, you should sprinkle your code with `strategically` placed `print` statements. – WJS Aug 06 '19 at 16:58

1 Answers1

2

This was originally closed as a dup of What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?

This answered at least part of the problem. You were getting that exception, and the dup does explain what causes the exception, though it doesn't address the specifics of your particular code.

(Aside: there are a lot of people, including me, who believe that questions like this where the OP expects someone else to debug their code are best answered by pointing the OP at somewhere with the information they need to find the solution for themselves. Directly solving the problem for the OP deprives the OP of the learning exercise of finding the solution themselves, and leads to people getting qualifications without actually knowing how to solve programming problems for themselves.)

Then you say this:

NOTE: PLEASE do not mark this as a duplicate, I have already made my String[] details variable to hold more than 1 array.

(It is a duplicate ... according to that is normally meant here by duplicate!)

That is the wrong fix. 1) It means that you didn't use the clues provided to understand what the problem really was. 2) It also implies a significant misconception about what happens when you assign an array.

Circling back, here is the logic process for diagnosing and fixing the problem:

Q: What has happened?

A: Got an exception.

Q: What does the exception mean?

A: Read javadocs, google it.

Q: Where did you get the exception?

A: You can get that from the stack trace (line number) and looking at the code.

Q: Why did you get the exception?

A: There will be clues in the exception message and the line what the exception was thrown. In this case it would say that you attempted to access element zero of an array whose length is zero. I am assuming that you haven't added / removed lines and line 30 is this one:

    String name = details[0];

Clearly you cannot access the zero'th element of an empty array. (Why? review your notes on arrays and how they are indexed!)

That gives you two things to look at:

  • Why was the array's length zero?
  • Why were you trying to access that element of a zero length (empty) array?

The first can be answered by reading through the javadoc for String::split, and thinking about it. The line you were trying to split must have been empty. (If there were any non-blank characters in it, the length of the array would have been > zero and you wouldn't have gotten an exception on line 30.)

If you look carefully at the input file you should be able to spot the empty line. (It could be at the end of the file.) And my guess is your problem's requirements mention the empty line. (They should.)

The second is simple. You didn't consider the possibility of an empty line in the input, and that would give you an empty array. Your code assumes that the array is non-empty.

Q: How do you fix it?

A: You need to know what you want to happen in each of those scenarios. Then you write code to implement that. Here are a couple of strategies:

  • Trim each line (to remove extraneous leading / trailing whitespace) and test if the resulting string has length zero. If it is, skip the line.
  • Split the line, and check how many elements there are in the array. If the number is NOT 4, do something appropriate. (Skip the line, report an error, whatever. You decide.)

Then test it.


Earlier I said this:

That is the wrong fix. ... 2) It also implies a significant misconception about what happens when you assign an array.

    String line = scan.nextLine();
    String[] details = new String[4];   // <<-- supposed fix
    details = line.split(" ");

Array assignment is actually a reference assignment. So the line after your fix is going to replace the 4 element array that you created with a new array created by the split call. The array may well have a different length. It will definitely be a different array.

In short, that fix actually doesn't have any effect.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216