【问题标题】:Random Generator always generates number 0随机生成器总是生成数字 0
【发布时间】:2017-03-22 19:39:22
【问题描述】:

我想知道为什么生成的第一个数字总是“0”。

代码如下:

public static void main(String[] args) {

    boolean[] pack = new boolean[52];
    int[] cards = new int[5];

    for (int i = 0; i < pack.length - 1; i++) {
        System.out.print(pack[i] + " | ");         
    }
    System.out.println();

    Random give = new Random();

    for (int i = 0; i < cards.length; i++) {
       while (pack[cards[i]])
            cards[i] = give.nextInt(5);  

       pack[cards[i]] = true;                 
       System.out.println(cards[i]);

    }

    for (int i = 0; i < pack.length - 1; i++) {
        System.out.print(pack[i] + " | ");         
    }     
}

【问题讨论】:

  • javascript != java
  • 另外,请格式化您的代码 - 目前它真的难以阅读。 (如果你把它做成一个 complete 程序也会有所帮助。你是如此接近,使用 main 方法 - 但只包括类声明和导入将有助于我们复制,粘贴,编译并运行。)
  • 这个give.nextInt(5),你是说give.nextInt(pack.length)吗?

标签: java arrays random


【解决方案1】:

因为pack(cards[i]) 在第一次迭代中始终为假。解决方案可能是实现do-while 而不是while

检查一下:

主要:

import java.util.Random;
public class hw {

       public static void main(String[] args) {

            boolean[] pack = new boolean[52];
            int[] cards = new int[5];

            for (int i = 0; i < pack.length - 1; i++) 
            {
                System.out.print(pack[i] + " | ");         
            }

            System.out.println();

            Random give = new Random();

            for (int i = 0; i < cards.length; i++) {
                do
                {
                    cards[i] = give.nextInt(5); 
                }
                while ( pack[cards[i]] );

                pack[cards[i]] = true;                 
                System.out.println(cards[i]);
            }

            for (int i = 0; i < pack.length - 1; i++) 
            {
                System.out.print(pack[i] + " | ");         
            }     
       }

}

输出:

假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |

4

3

0

1

2

真 |真实 |真实 |真实 |真实 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |假 |

【讨论】:

  • 非常感谢您的帮助,我一定会用您给我的解决方案审查代码
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-23
  • 2014-10-17
  • 2014-05-21
相关资源
最近更新 更多