Return ArrayList item instead of boolean

Juan CA :

In the following code, I define a method called loadItems, that it's supposed of creating an array list of type Item with each line of a text file.

  • The Item object is formed by a String that contains a name, and an int variable with a number.
  • Each line of the text file contains a name to store in a new item, followed by = and before that, the number that needs to be stored in the new item. Summarizing, each line looks something like: String=int.

The problem is that, instead of returning a new item and store it in the loadItems Array List, I get an error because it's supposed to return a boolean. I image this is caused because the new Item is created inside a while function that checks for a new line in the text file.

    ArrayList<Item> loadItems() throws FileNotFoundException {

        File phaseOneFile = new File("Phase-1.txt");
        Scanner readPhaseOneFile = new Scanner(phaseOneFile);

        while (readPhaseOneFile.hasNextLine()){
            String actualLine = readPhaseOneFile.nextLine();
            String[] actualLineToItem = actualLine.split("=");

            Item newItem = new Item();
            newItem.itemName=actualLineToItem[0];
            newItem.itemWeight= Integer.parseInt(actualLineToItem[1]);

            return loadItems().add(newItem);

        } 

    }
Federico klez Culloca :

A couple of things.

  • You return too early
  • You return the wrong thing
  • You use recursion for no discernible reason

First, you should return just after you have built your list, so remove the return.

Second, return the list after the loop ends

Third, accumulate stuff inside an actual ArrayList and return that instead of recursing.

Fourth, no need to return a concrete type, just return a List<Item>.

List<Item> loadItems() throws FileNotFoundException {

    File phaseOneFile = new File("Phase-1.txt");
    Scanner readPhaseOneFile = new Scanner(phaseOneFile);
    List<Item> items = new ArrayList<Item>();

    while (readPhaseOneFile.hasNextLine()){
        String actualLine = readPhaseOneFile.nextLine();
        String[] actualLineToItem = actualLine.split("=");

        Item newItem = new Item();
        newItem.itemName=actualLineToItem[0];
        newItem.itemWeight= Integer.parseInt(actualLineToItem[1]);

        items.add(newItem);

    } 

    return items;

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=127135&siteId=1