簡體   English   中英

詢問用戶輸入時如何打破 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());
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM