2014-10-29 53 views
-1

所以情況就是這樣。是否可以循環使用不同參數的方法?

我在做一個鍛鍊; Tibial,我不得不用我所有的靜態數字每個隨機數從外部文件lotto.dat

我必須做出一個方法doCompare()返回true或false比較。我的代碼後,我的問題就會出現:

public static void drawNumbers()throws Exception{ 

    Random rnd = new Random(); 

    int rndN1 = rnd.nextInt(19)+1; 
    int rndN2 = rnd.nextInt(19)+1; 
    int rndN3 = rnd.nextInt(19)+1; 
    int rndN4 = rnd.nextInt(19)+1; 
    int rndN5 = rnd.nextInt(19)+1; 
    int rndN6 = rnd.nextInt(19)+1; 

    System.out.println(); 
    System.out.println("Winner numbers: " + rndN1 + " " + rndN2 + " " + rndN3 + " " + rndN4 + " " + rndN5 + " " + rndN6); 

    String match = doCompare(rndN1); 

    if(match.equals("true")){ 

    System.out.println("Match on the number: " + rndN1); 

    } 
} 

那麼是否有可能以某種方式循環的「doCompare」與參數「doCompare(rndN1)」,然後rndN2,rndN3等要不然我應該怎麼做才能使這項工作?

+0

是使用一個循環... – brso05 2014-10-29 13:28:26

+0

但我怎麼做,第二次循環經歷改變參數爲rndN2而不是1? – user3703289 2014-10-29 13:29:22

+0

瞭解館藏,這太寬泛了,不成問題。 http://docs.oracle.com/javase/tutorial/collections/ – 2014-10-29 13:29:57

回答

0

創建一個可以收集整數的列表。創建一個循環來創建整數並將它們添加到列表中。在創建隨機整數時,您也可以在循環中創建輸出字符串。最後使用方法調用doComapre()的另一個循環,pealse將方法的返回值更改爲boolean。然後你可以在if語句中使用它,並且不必檢查返回值是否等於"true"

Random rnd = new Random(); 
    List<Integer> rndNumbers = new ArrayList<>(); 
    String outputString = "Winner numbers:"; 

    for(int i = 0; i < 6; i++) 
    { 
     rndNumbers.add(rnd.nextInt(19) + 1); 
     outputString = outputString + " " + rndNumbers.get(i); 
    } 

    System.out.println(); 
    System.out.println(outputString); 

    for(Integer curNumb : rndNumbers) 
    { 
     String match = doCompare(curNumb); 

     if (match.equals("true")) 
     { 
      System.out.println("Match on the number: " + curNumb); 
     } 
    } 

也許你可以使用數組,因爲你總是想要生成六個數字。對於字符串創建,您可以用Stringbuilder替換字符串。

1

使用適當的數據結構,像一個陣列或List到的隨機數和循環存儲超過它們:

List<Integer> numbers = new ArrayList<>(); 
for(int cout = 0 ; count < 6 ; ++count) { 
    numbers.add(rnd.nextInt(19)+1); 
} 
// ... 
for(int n : numbers) {  // go through all the numbers in the list 
    doCompare(n); 
} 
+0

可能應該用一個集合替換Array,以跳過重複項(可能這是他正在編寫的彩票繪圖應用程序) – Drejc 2014-10-29 13:31:15

+0

我不確定這一點。 – 2014-10-29 13:32:04

0

的最簡單的解決辦法是創建數組或列表和存儲RND號,然後循環在它上面

0

是的,你可以,但不是你想要做的。

,你必須創建rndNX列表值

像這樣:

List<Integer> rndList = new ArrayList<Integer>(); 

填充它,像這樣:

rndList.add(rnd.nextInt(19)+1); 
rndList.add(rnd.nextInt(19)+1); 
... 

,並使用列表:

for(final Integer rndI : rndList) 
{ 
    String match = doCompare(rndI); 
} 
0
Random rnd = new Random(); 

    System.out.println(); 

for(int i = 0; i < 6; i++) 
{ 
    int rndN = rnd.nextInt(19)+1; 

    String match = doCompare(rndN); 

    if(match.equals("true")){ 

    System.out.println("Match on the number: " + rndN1); 

    } 
} 

你可以做這樣的事情。根據需要首先初始化它們,而不是初始化所有的隨機數。

0

將int值存儲到數組或列表中並通過它進行循環。

相關問題