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

Time:03-06

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

CodePudding user response:

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);         
     } 
  }

CodePudding user response:

You could also set an empty country string before a do while loop and check for the the country not being empty in the end:

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):");

    String country = "";
    do
    {
        country = input.nextLine();
        if(!country.isEmpty()) {
            char c = country.charAt(0);

            if (Character.isUpperCase(c) == false)
            {
                System.out.println("Type with Capital Letter!");
            }
            else
            {
                countries.add(country);
            }
        }
    } while(!country.isEmpty());
}
  • Related