Hi I'm new to learning java/programing and I'm trying to create a function with the scanner class that reads the next line and appends it to an array list however my code doesn't work the way I want it to:
import java.util.ArrayList; import java.util.Scanner; public class arrayappendtest { public static void main(String[] args) { Scanner s = new Scanner(System.in); String tmp; ArrayList<String> sample = new ArrayList(); while (s.hasNext()) { System.out.println("Enter something (type quit to quit): "); tmp = s.nextLine(); if (tmp.equals("quit")){ break; } else{ sample.add(tmp); } } s.close(); System.out.println(sample); } }
when I run this block there is always an extra entry
test // this shouldn't be appended
Enter something (type quit to quit):
test1
Enter something (type quit to quit):
test2
Enter something (type quit to quit):
quit
Enter something (type quit to quit): // this shouldn't print either
[test, test1, test2]
I don't understand why this is happening / what would be the best practice to solve I'm not appending anything until I get to my while loop.
Thank you