I need to write a method to take user input car specs and add them into an ArrayList. This needs to accept any amount of specs the user wants to input, including none.
This is my first post here, so apologies for any poor syntax.
public static ArrayList getTrim() {
Scanner t = new Scanner(System.in);
System.out.println("Enter car trim");
ArrayList<String> trim = new ArrayList<>();
while (t.hasNext()) {
trim.add(t.next());
}
return trim;
}
I thought this condition would return false if whitespace was entered. This continues iterating and can only be exited manually.
I also tried
if (t.hasNext()) {
trim.add(t.next());
}
else {
t.close();
}
This iterates once and then returns the ArrayList, but I need to be able to input more. Changing my if or while condition to hasNextLine() gives the same results stated, here I used hasNext() because car trim levels have certain format expectations. I do not understand why hasNext() will not return as false when no input is given.
>Solution :
You can try this:
public static ArrayList getTrim() {
Scanner t = new Scanner(System.in);
System.out.println("Enter car trim");
ArrayList<String> trim = new ArrayList<>();
while (t.hasNext()) {
if (!t.next().trim().equals("") {
trim.add(t.next());
}
else {
t.close();
}
}
return trim;
}