Closed. This question needs details or clarity。它当前不接受答案。












想改善这个问题吗?添加详细信息并通过editing this post阐明问题。

2个月前关闭。



Improve this question





到目前为止,我还是编码新手,我真的很喜欢。但是我在程序上遇到了困难。以下代码的任何帮助将使我更接近解决方案。如果我的代码不好,我深表歉意。 X是我要解决的问题,我什至不知道要尝试什么。谢谢

public class Dice {

    public static void main(String[] args) {
       Scanner input  = new Scanner(System.in);
       System.out.println("How many sides do your die have");
       int amountOfSides = input.nextInt();
       System.out.println("How many times to roll, enter an amount");
       int rollAmount = input.nextInt();
       rolledDie(rollAmount, amountOfSides);
    }

    public static void rolledDie(int rollAmount, int amountOfSides) {
       int[] dieRoll = new Random().ints(rollAmount,1,amountOfSides).toArray();
       System.out.println("Number of rolls: "+rollAmount+ ""
            + "\n"+"Number of sides in your die: "+amountOfSides);
       System.out.println("\n"+"You rolled: "+ java.util.Arrays.toString(dieRoll));
       for (int i = 1; i <= rollAmount; i++) {
          System.out.println("\n"+"Side: "+i+" Appeared: "+ X + " time(s)");
       }
    }
}

最佳答案

这条线有问题:

int[] dieRoll = new Random().ints(rollAmount,1,amountOfSides).toArray();


如果您查看Random.ints()的文档,您会发现range参数中的第二个是互斥的-即您不会获得这些值。因此,您需要添加一个:

int[] dieRoll = new Random().ints(rollAmount,1,amountOfSides+1).toArray();


关于每个值出现的次数,创建一个数组来保存计数,并每次通过dieRoll在适当的索引处递增值:

int[] count = new int[amountOfSides];
for (int i = 0; i < rollAmount; i++) {
    count[dieRoll[i]-1] += 1;
}


请注意,由于Java数组的索引为零,因此您需要将roll值减一。

要打印出每个值出现的次数,您要遍历count而不是dieRoll

for (int i = 1; i <= amountOfSides; i++) {
   System.out.println("\n"+"Side: "+i+" Appeared: "+ count[i-1] + " time(s)");
}


完整的方法如下:

  public static void rolledDie(int rollAmount, int amountOfSides) {
    int[] dieRoll = new Random().ints(rollAmount,1,amountOfSides+1).toArray();
    System.out.println("Number of rolls: "+rollAmount+ ""
         + "\n"+"Number of sides in your die: "+amountOfSides);
    System.out.println("\n"+"You rolled: "+ java.util.Arrays.toString(dieRoll));

    int[] count = new int[amountOfSides];
    for (int i = 0; i < rollAmount; i++) {
        count[dieRoll[i]-1] += 1;
    }

    for (int i = 1; i <= amountOfSides; i++) {
       System.out.println("\n"+"Side: "+i+" Appeared: "+ count[i-1] + " time(s)");
    }
  }


对于rolledDie(10, 6),您将获得:

Number of rolls: 10
Number of sides in your die: 6

You rolled: [2, 2, 1, 3, 2, 1, 4, 1, 6, 3]

Side: 1 Appeared: 3 time(s)

Side: 2 Appeared: 3 time(s)

Side: 3 Appeared: 2 time(s)

Side: 4 Appeared: 1 time(s)

Side: 5 Appeared: 0 time(s)

Side: 6 Appeared: 1 time(s)

10-07 13:11