2015-08-28 29 views
0

我仍然在學習java,但我想要做的程序是一個數字選擇器根據我自己的規則。簡單地說,你有1-10,你根據你選擇的數字選擇一個數字來決定你必須從中選擇哪些數字。只是好奇的最好的方式,使這個Java程序

例如,數字將爲1-10。如果我選擇1,它會顯示我可以選擇的其他數字(2,5,7,8),然後選擇另一個數字後,它會將我的數字限制爲5,7(因爲我選擇了2,所以刪除8)。

我只是想知道是否有更好的方法來做這個,除了一堆if/else語句和所有我可以選擇的數字,如果我選擇1.做一個所有可能的數字數組可能會很好,但由於這些數字更隨機,因此刪除的數字如何呢?

+3

如何從集合'(1,2,3,...,10)'中選擇'1'生成集合'(2,5,7,8)'? –

+1

聽起來像功課。你可以發佈你已經嘗試過嗎?你只能使用數組嗎?該計劃的要求是什麼? –

回答

0

您可以使用switch聲明。它將提供您選擇不同的選項,而不使用if聲明,這更清楚。

舉例來說,如果你有一個number變量(在您通過Scanner輸入號碼的情況下):

int number = scanner.nextInt(); 

而且你有switch聲明是這樣的:

switch (number) { 
      case 1: 
        System.out.println("You choose option 1"); 
        //Code when the user input it's 1 
        break; 
      case 2: 
        System.out.println("You choose option 2"); 
        //Code when the user input it's 2 
        break; 
      case 3: 
        System.out.println("You choose option 3"); 
        //Code when the user input it's 3 
        break; 
      case 4: 
        System.out.println("You choose option 4"); 
        //Code when the user input it's 4 
        break; 
      case 5: 
        System.out.println("You choose option 5"); 
        //Code when the user input it's 5 
        break; 
} 

我希望這會對你有所幫助!

0

這對你有用嗎? (當然這是僞代碼)

Set original = //Fill with {1,2,...10} 
Set selectedSoFar = new HashSet(); 
while(original.isEmpty() ==false){ 
    int selectedNow = selectOne(original) 
    selectedSoFar.add(selectedNow) 
    original.remove(selectedNow) 
} 
private int selectOne (Set selection){ 
    int selected = -1 
    while (!selection.contains(selected)){ 
    // Print the selection. 
    //Ask the user to type one of the number 
    //assign it to "selected" 
    } 
    return selected 
} 

很明顯,你可以在剩下的代碼填寫用於填充原設定以及莫名其妙閱讀選擇在「selectOne」 希望這有助於!

------- -------更新

對不起,我習慣了Scala的不可變的集合,所以我不得不改變我原來的答覆適合的Java。