我必須根據拼字遊戲的計分規則,其得分的用戶輸入的字符串下面的代碼:把switch語句到循環的java
import java.util.Scanner;
public class ScrabbleScorer {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
System.out.print ("Enter string: ");
String str = sc.nextLine();
int score = computeScore (str);
System.out.println ("The score for '" + str + "' is: " + score);
sc.close();
}
public static int computeScore (String str) {
str = str.toUpperCase();
int score = 0;
for(int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
switch(ch){
case 'A': score = score + 1;break;
case 'B': score = score + 3;break;
case 'C': score = score + 3;break;
case 'D': score = score + 2;break;
case 'E': score = score + 1;break;
case 'F': score = score + 4;break;
case 'G': score = score + 2;break;
case 'H': score = score + 4;break;
case 'I': score = score + 1;break;
case 'J': score = score + 8;break;
case 'K': score = score + 5;break;
case 'L': score = score + 1;break;
case 'M': score = score + 3;break;
case 'N': score = score + 1;break;
case 'O': score = score + 1;break;
case 'P': score = score + 3;break;
case 'Q': score = score + 10;break;
case 'R': score = score + 1;break;
case 'S': score = score + 1;break;
case 'T': score = score + 1;break;
case 'U': score = score + 1;break;
case 'V': score = score + 4;break;
case 'W': score = score + 4;break;
case 'X': score = score + 8;break;
case 'Y': score = score + 4;break;
case 'Z': score = score + 10;break;
default : score = score;
}
}
return score;
}
}
我在想,如果有包裹switch
成loop
,這樣的方式它不需要用手寫出26次。謝謝
嗯,是的,將輸入獲取代碼封裝到一個無限循環中,並解析一個特殊的輸入以便退出。 – Mena