需要帮助根据用户输入随机化数字

时间:2016-12-19 03:16:22

标签: java

    public class numberCube {

    public static int size;
    public static int tosses;
    public static int random;
    public static int value;
    public static int values;


    public static void cubeSize(){

//获取允许随机化的数字范围

String x = JOptionPane.showInputDialog
                ("How many numbers do you want on your cube?");

        int size = Integer.parseInt(x);

    }
    public static void numTosses(){

//获取随机数发生器循环的次数

 String y = JOptionPane.showInputDialog
                ("How many times do you want to toss the dice?");

        int tosses = Integer.parseInt(y);

    }

    public static void randomizer(){

//创建随机数。这是问题所在。我需要能够//允许用户指定数字的范围以及随机化的次数   例如,对于cubeSize(),我可以输入3,而对于numTosses(),我可以输入5.可能的输出是:1,1,3,2,3

    }

 }
}

2 个答案:

答案 0 :(得分:0)

你在这里重复变量(ex: size,tosses,etc)的初始化。

如果想要操纵特定类的属性,则需要使用this关键字。所以,

int size = Integer.parseInt(x);变为this.size = Integer.parseInt(x);

int tosses = Integer.parseInt(y);变为this.tosses = Integer.parseInt(y);

etc..

然后在您的randomizer()方法中,您可以尝试以下内容:

Random random = new Random();
for (int i = 1; i <= this.tosses; i++) {
    int value = 1 + random.nextInt(this.size);
    System.out.println(value);
}

答案 1 :(得分:0)

你的意思是这样的吗?

Random r = new Random();
for (int i = 0; i < numTosses; ++i) {
    int rand = 1 + r.nextInt(cubeSize);
    // use rand, which will be an integer from 1 to cubeSize (inclusive)
}