2014-02-08 17 views
1

嗨,我有這個問題。這是情況。有四種選擇添加字符到用戶選擇

  1. [1]黑色
  2. [2]紅色
  3. [3]藍色

例如,如果用戶選擇任意的這個數字的代碼將打印:

你選擇黑色 這裏是我到目前爲止的代碼

System.out.print("Course: \n[1] BSIT \n[2] ADGAT \n[3] BSCS \n[4] BSBA \n[5] NITE \n enter course:"); 
course=Integer.parseInt(input.readLine()); 

問題是,當我打電話給system.out.print(「」+ course);它打印數字而不是單詞本身?

回答

1

無法打印沒有任何數據結構的課程。如果你想將數字與某種數據聯繫起來,你需要自己去做。例如存儲在名字數組:

String[] names = {"BSIT","ADGAT","BSCS","NITE"}; 

然後引用與相應的查找你的數組:

//... 
int course = Integer.parseInt(input.readLine()); 
System.out.println("You chose: " + names[course-1]); 

記住使用數組時,所以我們減少一個編制索引從零開始。

0

你在那兒做什麼: 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()); 
} 

我喜歡這種方式,因爲現在這個程序實際上知道有一個叫「課程」特別的東西。它知道這是一個數字,一些數字可能實際上反映了選擇的課程。它在一箇中心位置完成(課程的定義)。

希望這不是太多的信息,你會看到這是有幫助的。

+0

好的T-我的版本是一個比我所謂的「直截了​​當」更短。你從那裏做什麼主要取決於你多久需要這個?它是一次完成,你只是想盡快完成這項工作。去尋找最簡單(或最短)的解決方案。如果'課程'是你想要傳遞的程序中的重要內容?轉到單獨的數據結構(類型) - 枚舉解決方案。從長遠來看這是值得的! – tilois

0

使用本

switch(course) 
     { 
     case 1: 
      System.out.println("black"); 
      break; 
     case 2: 
      System.out.println("red"); 
      break; 
     case 3: 
      System.out.println("blue"); 
      break; 
     default: 
      System.out.println("invalide number"); // this will execute if course var does not equale to 1 , 2 or 3 
      break; 

     }