2016-11-05 112 views
0

我有一個我正在寫的程序,它是將單詞翻譯成豬拉丁語(真正基本的練習) 我可以讓輔音變成豬拉丁語沒有問題,但另一方面是我需要檢查第一個字母是否是輔音,如果不是,那麼翻譯會發生變化。如果第一個字母是一個輔音,則返回一個布爾值

我已經建立了一個方法來檢查一個單詞的第一個字母是否是一個輔音,如果它是返回一個布爾值爲true否則爲false。

出於某種原因,這種方法不會運行「否則」語句

下面是被寫入的方法。

private static boolean firstLetterConsonant(String s) 
{ 
    boolean isConsonant; 

    //check to see if the first letter is not a vowel 
    if(s != "a" && s != "e" && s != "i" && s != "o" && s != "u") 
    { 
     isConsonant = true; 
    } else { 
     isConsonant = false; 
    } 
    return isConsonant; 
} 

作爲側面註釋,該方法正在傳遞用戶在程序中其他位置輸入的字符串。

+2

你沒有檢查第一個字母,你正在檢查整個字符串。 'char c = s.charAt(0)' – Tibrogargan

+0

@Techiee不會得出結論。我沒有降低你的...直到現在 – Tibrogargan

+0

@Tibrogargan:對不起。 @憲兵:我寫了答案,他比較字符串,而不是字符,我知道是不正確的。 – Techiee

回答

4

您有3個選項。

  1. 使用String#startsWith()和if條件檢查5個元音(就像你在做什麼)

  2. 採取的第一個字符出使用String#charAt()字符串,並檢查它是否是一個元音(和返回假如是這樣的話)。

  3. 使用String#matches和使用"(?i)[^aeiou].*"

+0

最後一個錯過首都,不是?的字符數組。另外,'-1 ==「aeiou」.indexOf(s.substring(0,1).toLowerCase())'XD – Tibrogargan

+0

@Tibrogargan - 編號'?i'選項使匹配不區分大小寫。它檢查資本和小型字符。 – TheLostMind

+1

你只是偷偷在那裏:) – Tibrogargan

0

這的確是一個很簡單的解決方案。

private static boolean firstLetterConsonant(String s) { 
    boolean isConsonant = true; 

    if ("".equals(s)) 
     return false; 

    //check to see if the first letter is not a vowel 
    switch(s.charAt(0)) { 
     case 'A': 
     case 'a': 
     case 'E': 
     case 'e': 
     case 'I': 
     case 'i': 
     case 'O': 
     case 'o': 
     case 'U': 
     case 'u': isConstant = false; 
    } 
    return isConsonant; 
} 

您正在檢查字符串本身,但您應該只檢查第一個字符。


或者你可以只使用String.matches功能,並通過在"(?i)[^aeiou].*"。正則表達式更好。

+1

當第一個字母是**而不是輔音時,你返回'true'。 – QBrute

+0

哈哈溜出去。修復。 – Jay

1

只要你能做到這樣:

當您將字符串值這個方法,你應該檢查它是否爲空或不爲空。因爲如果字符串值爲空,它將引發空指針異常。

private static boolean firstLetterConsonant(String s) 
{ 
char l = s.toLowerCase().trim().charAt(0); 
//check to see if the first letter is not a vowel 
if (l!='a' && l!='e' && l!='i' && l!='o' && l!='u')) { 
    return true; 
} 
return false; 
} 
+0

如果用'false'初始化'isConsonant',則可以刪除'else'塊。 – QBrute

+0

是的。謝謝。 –

+0

@QBrute你甚至不需要'isConsonant'。 '如果(1!='a'[...])返回true;返回false;'。 – Gendarme

相關問題