2014-10-29 82 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值存储到数组或列表中并通过它进行循环。

相关问题