Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

never ending loop for user populated arraylist

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;

}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading