簡體   English   中英

為什么跳過if-else語句的else部分?

[英]Why is it skipping the else part of my if-else statement?

它一直在跳過我聲明的其他部分。 如果不滿足所有其他限制,我只希望它從無效行中打印出來。

import java.util.Scanner;
public class Program_3
{
   public static void main(String[] args)
   {
      Scanner input = new Scanner(System.in);
      System.out.print("Enter a password: ");
      String str = input.nextLine();
      boolean lowerCase = false;
      boolean upperCase = false;
      boolean number = false;
      char y;
      for (int i = 0; i < str.length(); i++)
      {
         y = str.charAt(i);
         if(Character.isUpperCase(y))
         {
            upperCase = true;
         }
         else if(Character.isDigit(y))
         {
            number = true;
         }
         else if(Character.isLowerCase(y))
         {
            lowerCase = true;
         }
      }
      if (lowerCase == true)
      {
         if (upperCase == true)
         {
            if (number == true)
            {
               if (str.length() >= 8)
               {
                  System.out.println("Verdict:\t Valid");
               }
            }
         }
      }
      else
         System.out.println("Verdict:\t Invalid");
   }
}

如果不滿足所有條件,為什么會跳過而不打印無效行?

代碼中的else僅與最外部的 if 因此,只有在lowerCase == false時才執行。

要解決此邏輯,請將所有三個條件合並為一個if ,即:

  if (lowerCase == true && upperCase == true && number == true && str.length() >= 8)
  {
      System.out.println("Verdict:\t Valid");
  }
  else
     System.out.println("Verdict:\t Invalid");

旁注,布爾值不需要與true進行顯式比較,因此可以將其寫得更短:

      if (lowerCase && upperCase && number && str.length() >= 8)

else條件放置在錯誤的位置,只有在lowerCase條件為false才能達到。 而且無論如何,我們可以在單個條件下簡化和組合所有if ,您的意思是:

if (lowerCase && upperCase && number && str.length() >= 8) {
   System.out.println("Verdict:\t Valid");
} else {
   System.out.println("Verdict:\t Invalid");
}

可以簡化此代碼以顯示控制流:

  if(lowerCase == true)
  {
      //lowerCase == true -> execute this code
      if( upperCase == true)...
  }else
      //lowerCase == false -> execute this code
      ...

如果條件為false,則內部if語句(排他的btw。)不會執行外部else語句。 您的代碼的邏輯正確版本為:

if(lowerCase && upperCase && isNumber && str.length() > 8)
    System.out.println("Verdict:\t Valid");
else
    ...

您的測試密碼至少包含一個小寫字符。 只要這樣做,else語句就永遠不會執行。 要測試“如果所有條件都成立...否則...”,請嘗試以下方法:

if (lowerCase && upperCase && number && str.length >= 8) {
    // password ok
} else {
    // password not ok
}

順便說一句,如您所見,由於不需要,我不使用lowerCase == true ,lowerCase已經是一個布爾值。

暫無
暫無

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

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