簡體   English   中英

如何檢查方法是否返回 true 或 false?

[英]How do I check if a method returns a true or false?

所以我有這個代碼

public static boolean isVowel (char c) { 

        if (c=='a'||c=='e'||c=='i'||c=='o'||c=='u')
        {
            return true;
        }

        else
        {
            return false;
        }
    }

和這個代碼在兩個單獨的方法

    if (isVowel == true()) //I know this is wrong but how could I make it work?
        {
            //run command
        }
        else 
        {
            //run command
        }

if (isVowel())測試if isVowel真,我該如何進行測試?

public static boolean isVowel (char c) { 
    // concise code here
    return (c=='a'|| c=='e'|| c=='i'|| c=='o'|| c=='u');
}

// your fix here
if (isVowel(aCharVariable)) {
    // your code here
} else {
    // your code here
}

簡潔明了。

我不知道我的問題是否正確,但我認為以下是滿足您要求的:

if (isVowel(/* put a char here */) == true) {
     // Do stuff
} else {
    // Do other stuff
}

在這種情況下(因為isVowel()boolean類型,您也可以這樣做,這更優雅:

if (isVowel(/* put a char here */)) {
    // Do stuff...

這是可能的,因為 if 語句檢查的條件只是布爾狀態( truefalse )。

在 Java 中, if語句檢查其操作數是true還是false 操作數只能是boolean類型(並且在一定程度上是裝箱Boolean變量)。

boolean b = true;
if (b) {
  System.out.println("b was true");
}

除了將靜態值/文字true分配給變量之外,您還可以分配方法調用的結果:

boolean b = isVowel('a');
if (b) {
  System.out.println("a is a vowel");
}

現在,您不一定需要該變量,您可以內聯它並直接使用方法調用的結果:

if (isVowel('e')) {
  System.out.println("e is a vowel too");
}

請注意,某些運算符,例如==!=<返回布爾值:

boolean greater = 5 > 3;
boolean equal = null == null;
boolean different = new Object() == new Object();

if (greater) {
  System.out.println("5 is greater than 3");
}

if (equal) {
  System.out.println("null equals null");
}

if (different) {
  System.out.println("Two object instances have different idententity");
}

當然,這里不需要變量,可以將比較表達式直接放入if中:

if (5 > 3) {
  System.out.println("5 is greater than 3");
}

if (null == null) {
  System.out.println("null equals null");
}

if (new Object() == new Object()) {
  System.out.println("Two object instances have different idententity");
}

甚至:

if ((5 < 3) == false) {
  System.out.println("The (logical) statement '5 is less than 3' is false. Therefore, the result of the boolean comparison is true and this code is executed");
}

擺脫所有 ors 的另一種寫法。

private static final Set<Character> VOWELS = ImmutableSet.of('a','e','i','o','u');
public boolean isVowel(char c) {
    return VOWELS.contains(c);
}

if(isVowel('a')) {
  //do stuff
}

暫無
暫無

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

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