0

The method should read the contents of a file line by line and add each line to the array list. It should end once it reaches a solitary "." (period) or no more lines.

The problem is that I can not figure a way to check the contents of the next line without skipping lines since I am using nextLine numerous times. I am limited to the use of hasNext and nextLine.

public static ArrayList<String> getList(Scanner in) {
 ArrayList<String> list = new ArrayList<String>();

 while(in.hasNext() && !in.nextLine().equals("."))
  {list.add(in.nextLine());}

return list;}

As written the output will skip lines to output lines 2, 4, 6 etc when I need it to output 1,2,3,4 etc.

I am sure I am simply not seeing the way to solve the issue but any hints specifically on how to get it working by reformatting what I have with the methods listed are appreciated.

Thumper
  • 35
  • 6
  • I am probably missing something in the "duplicate" thread since I don't really see how it relates to my question, as my question is specifically about how to reformat the code I have using the tools available to get the desired output. – Thumper Apr 09 '16 at 22:47

1 Answers1

2

Just store the line in a variable:

public static List<String> getList(Scanner in) {
    List<String> list = new ArrayList<String>();

    while (in.hasNextLine()) {
        String line = in.nextLine();
        if (line.equals(".")) {
            break;
        }
        else {
            list.add(line);
        }
    }
    return list;
}
JB Nizet
  • 633,450
  • 80
  • 1,108
  • 1,174
  • The `else` isn't necessary. – Alex Hall Apr 09 '16 at 21:45
  • But it makes the code easier to read, IMO. – JB Nizet Apr 09 '16 at 21:46
  • 1
    I disagree but I'm not going to debate that. I just thought OP should know that it's optional. – Alex Hall Apr 09 '16 at 21:47
  • I tried using what you gave me but it doesn't seem to output anything from the file I am reading in. I did figure out another way with the help of a friend here that works. I will fiddle around with the one you gave me and see if I am doing something wrong also. Thanks for the help. – Thumper Apr 09 '16 at 22:48