How to add comma seperated string and int into two different arraylists [java]

Viewed 53

Say I have strings and integers being read from a file and seperated by a comma and I want to add them into two different arrayLists.

hamburger,15

cheese,10

soda,15

How would I go about doing this? I intially used nextLine() to add them into one arraylist and extract the integer and erase the comma but this wasn't working for arrayLists. I also tried using nextInt() to just grab the int's but was given an exception.

  public static void readFile(ArrayList items, ArrayList cost)
  {
    String intValue = "";
    try
    {
      Scanner read = new Scanner(new File("Menu.txt"));
      while (read.hasNext())
      {
        items.add(read.nextLine());
      }
      read.close();
      for (int i = 0; i < items.size(); i++)
      {
        intValue = items.indexOf(i).replaceAll("[^0-9]", "");
        int value = Integer.parseInt(intValue);
        cost.add(value);
      }
      System.out.println(item);
      System.out.println(cost);
    }
    catch(FileNotFoundException fnf)
    {
      System.out.println("File was not found.");
    }
  }

my end result would be:

items = [hamburger, cheese, soda]

cost = [15, 10, 15]

1 Answers
public static void readFile(List<String> items, List<Integer> costs) {
    try {
        Scanner read = new Scanner(new File("Menu.txt"));
        while (read.hasNext()) {
            String line = read.nextLine();
            String[] itemsAndCosts = line.split(",");
            items.add(itemsAndCosts[0]);
            costs.add(Integer.parseInt(itemsAndCosts[1]));
        }
        read.close();
        System.out.println(items);
        System.out.println(costs);
    } catch (FileNotFoundException fnf) {
        System.out.println("File was not found.");
    }
}
  1. Use List<String> instead of ArrayList.
  2. You can split the line on the , and then you have an array of 2 elements, item and cost. (Note: will only work if there is only one , per line). You can also use .subString(...), but for me, splitting is cleaner.
  3. Use try-with-resources so you don't need to do .close():
try (Scanner read = new Scanner(new File("Menu.txt"))) {
    while (read.hasNext()) {
        String line = read.nextLine();
        String[] itemsAndCosts = line.split(",");
        items.add(itemsAndCosts[0]);
        costs.add(Integer.parseInt(itemsAndCosts[1]));
    }
    System.out.println(items);
    System.out.println(costs);
} catch (FileNotFoundException fnf) {
    System.out.println("File was not found.");
}
Related