2011-12-12 160 views
2

我是新來的java,我試圖要求用戶輸入,但我不希望用戶能夠輸入兩次相同的數字。以下是我試圖用戶輸入,不允許相同的輸入兩次

  g1 = iBox.getInteger("Enter your 1st number"); 
      g2 = iBox.getInteger("Enter your 2nd number"); 
       if(g1 == g2){ 
        g2 =iBox.getInteger("Number used, please re-enter"); 
       } 
      g3 = iBox.getInteger("Enter your 3rd number"); 
       if(g3 == g1){ 
        g3 =iBox.getInteger("Number used, please re-enter"); 
       } 
       else if(g3 == g2){ 
        g3 =iBox.getInteger("Number used, please re-enter"); 
       } 
      g4 = iBox.getInteger("Enter your 4th number"); 
       if(g4 == g1){ 
        g4 =iBox.getInteger("Number used, please re-enter"); 
       } 
       else if(g4 == g2){ 
        g4 =iBox.getInteger("Number used, please re-enter"); 
       } 
       else if(g4 == g3){ 
        g4 =iBox.getInteger("Number used, please re-enter"); 
       } 
      oBox.print(" " + g1 + " " + g2 + " " + g3 + " " + g4 + " "); 
+1

你有什麼問題嗎? – chance

+0

這裏沒有問題。 「iBox」是什麼類型? –

+0

我們可以獲得更多信息嗎?拋出什麼異常(如果有的話)?想必你正在經歷意想不到的行爲。你能詳細說明這種行爲嗎?我很樂意提供幫助;我只需要知道什麼不適用於您的代碼(因爲乍一看,它看起來不錯) –

回答

1
  • 拿一個ArrayList
  • 掃描從用戶的價值,分析,驗證添加到ArrayList
  • 做來檢查它是否在list
  • 已經存在
1

我建議您將以前的輸入存儲在List或某種集合中。然後,您可以使用.contains(Object o)方法查看該集合是否已包含特定值。

這將允許您擴展您的應用程序超出固定數量的輸入。

Collection API

3

你應該使用循環和一組。 Pseudocode:

let S be the set of used numbers(or array, if order is important) 
clear contents of S 
for I = 1 to N, where N is the number of numbers you want to get 
    int g = iBox.getInteger("Enter Ith number"); 
    while(S.contains(g)) 
     g = iBox.getInteger("Number used, please re-enter"); 
    Add g into S. 
相關問題