[英]Java Switch Statement - Is "or"/"and" possible?
我實現了一個字體系統,它通過 char switch 語句找出要使用的字母。 我的字體圖像中只有大寫字母。 我需要做到這一點,例如,'a' 和 'A' 都具有相同的 output。不是有 2 倍的案例數量,而是像下面這樣的東西:
char c;
switch(c){
case 'a' & 'A': /*get the 'A' image*/; break;
case 'b' & 'B': /*get the 'B' image*/; break;
...
case 'z' & 'Z': /*get the 'Z' image*/; break;
}
這在 java 中可能嗎?
您可以通過省略break;
來使用switch-case break;
聲明。
char c = /* whatever */;
switch(c) {
case 'a':
case 'A':
//get the 'A' image;
break;
case 'b':
case 'B':
//get the 'B' image;
break;
// (...)
case 'z':
case 'Z':
//get the 'Z' image;
break;
}
...或者您可以在switch
之前switch
標准化為小寫或大寫 。
char c = Character.toUpperCase(/* whatever */);
switch(c) {
case 'A':
//get the 'A' image;
break;
case 'B':
//get the 'B' image;
break;
// (...)
case 'Z':
//get the 'Z' image;
break;
}
以上,你的意思是OR而不是AND。 AND的例子:110&011 == 010這不是你要找的東西。
對於OR,只有2個沒有中斷的情況。 例如:
case 'a':
case 'A':
// do stuff
break;
以上都是很好的答案。 我只是想補充一點,當有多個字符需要檢查時,if-else可能會變得更好,因為您可以改為編寫以下內容。
// switch on vowels, digits, punctuation, or consonants
char c; // assign some character to 'c'
if ("aeiouAEIOU".indexOf(c) != -1) {
// handle vowel case
} else if ("!@#$%,.".indexOf(c) != -1) {
// handle punctuation case
} else if ("0123456789".indexOf(c) != -1) {
// handle digit case
} else {
// handle consonant case, assuming other characters are not possible
}
當然,如果這變得更復雜,我建議使用正則表達式匹配器。
對一個有趣的Switch case
陷阱的觀察 - > fall through
switch
“break語句是必要的,因為沒有它們,switch塊中的語句就會失敗:” Java Doc的例子
連續case
片段沒有break
:
char c = 'A';/* switch with lower case */;
switch(c) {
case 'a':
System.out.println("a");
case 'A':
System.out.println("A");
break;
}
這種情況的O / P是:
A
但是如果改變c的值,即char c = 'a';
那么這很有趣。
這種情況的O / P是:
a A
即使第二種情況測試失敗,程序也會進入打印A
,由於缺少break
而導致switch
將其余代碼視為一個塊。 匹配的案例標簽之后的所有語句都按順序執行。
增強的 switch/case / Switch with arrows語法(自 Java 13 起):
char c;
switch (c) {
case 'A', 'a' -> // c is either 'A' or 'a'.
}
根據我對您的問題的理解,在將字符傳遞給switch語句之前,您可以將其轉換為小寫。 因此,您不必擔心大寫,因為它們會自動轉換為小寫。 為此,您需要使用以下功能:
Character.toLowerCase(c);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.