询问用户输入时如何打破 while 循环?

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

我需要尝试在用户输入空行而不是国家时打破 while 循环。这是我到目前为止所做的代码,它似乎不想结束询问国家/地区的循环:

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

用户输入应如下所示:

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

您正在检查 hasNext(),但应该检查 hasNextLine()

但是,两者都不要做:

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

您还可以在 do while 循环之前设置一个空的国家/地区字符串,并检查最后国家/地区是否为空:

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