你在那兒做什麼: 1.你打印出一句話。 2.你讓用戶輸入一個句子,你希望包含一個數字並將其轉換爲這樣的句子。
程序本身並不知道你給用戶的第一句話其實是他應該選擇的不同的東西的選擇。
你需要的是將數字轉換回它實際表示的東西。
最簡單的方法將是一個
String word;
switch(course) {
case 1: word = "BSIT"
break;
case 2: word = "ADGAT";
break;
case 3: word = "BSCS";
break;
case 4: word = "BSBA";
break;
case 5: word = "NITE";
break;
default:
throw new IllegalArgumentException("The choice '" + course + "' is not a valid one. Only 1-5 would be legal);
}
System.out.println("The course you've chosen is: " + word);
這是最直接的方式來寫,但實際上不是我喜歡的,因爲它複製在映射完成的地方。我寧願居然告訴程序什麼這些東西,如:
private enum Courses {
BSIT(1), ADGAT(2), BSCS(3), BSBA(4), NITE(5);
private int userChoice;
private Courses(int theUserChoice) {
userChoice = theUserChoice;
}
public int getUserChoice() {
return userChoice;
}
public static fromUserChoice(int aChoice) {
for (Courses course: Courses.values() {
if (course.userChoice == aChoice) {
return course;
}
throw new IllegalArgumentException("The choice '" + course + "' is not a valid one. Only 1-5 would be legal);
}
}
}
private static String printCourseList() {
System.out.print("Courses: ");
for (Courses course: Courses.values()) {
System.out.print("[" + course.getUserChoice() + "] " + course.name() + " ");
}
System.out.println();
}
public static main(String[] args) {
printCourseList();
Courses course = Courses.fromUserChoice(Integer.valueOf(System.console().readLine()));
System.out.println("You're selected course is: " + course.name());
}
我喜歡這種方式,因爲現在這個程序實際上知道有一個叫「課程」特別的東西。它知道這是一個數字,一些數字可能實際上反映了選擇的課程。它在一箇中心位置完成(課程的定義)。
希望這不是太多的信息,你會看到這是有幫助的。
好的T-我的版本是一個比我所謂的「直截了當」更短。你從那裏做什麼主要取決於你多久需要這個?它是一次完成,你只是想盡快完成這項工作。去尋找最簡單(或最短)的解決方案。如果'課程'是你想要傳遞的程序中的重要內容?轉到單獨的數據結構(類型) - 枚舉解決方案。從長遠來看這是值得的! – tilois