Skip to content
Advertisement

how do I break a while loop when asking for user input?

i need to try to break the while loop when a user enters an empty line instead of countries. Here is the code I have done so far and it does not seem to want to end the loop of asking for countries:

public void userInterface()
    {
    // interactive interface
      Scanner input = new Scanner(System.in);

      System.out.println("Enter the date:");
      String date = input.nextLine();

      ArrayList<String> countries = new ArrayList<String> ();
      
      System.out.println ("Enter the list of countries (end with an empty line):");
      
      while (input.hasNext()) {
         String country = input.nextLine();
         
         if (country.isEmpty()){
            break;
         } 
             
         char c = country.charAt(0);
         
         if (Character.isUpperCase(c)==false){
            System.out.println ("Type with Capital Letter!");
         } else {
            countries.add(country);         
         } 
      }
    
   
   }

the user input should look as follows:

Enter the date:
2022-02-17
Enter the list of countries (end with an empty line):
Norway
Suriname
South Namibia

Advertisement

Answer

Your checking for hasNext() but should be checking for hasNextLine().

However, don’t do either:

while (true) {
     String country = input.nextLine();
     
     if (country.isEmpty()){
        break;
     } 
         
     char c = country.charAt(0);
     
     if (!Character.isUpperCase(c)){
        System.out.println ("Type with Capital Letter!");
     } else {
        countries.add(country);         
     } 
  }
Advertisement