gpt4 book ai didi

java - 我怎样才能显示一个数字出现的次数

转载 作者:行者123 更新时间:2023-12-01 17:28:47 24 4
gpt4 key购买 nike

到目前为止,我还是编码新手,我真的很喜欢它。但我在一个程序上遇到了困难。对以下代码的任何帮助都会让我更接近解决方案。如果我的代码不好,我深表歉意。 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() 的文档您会看到范围参数中的第二个是排他的 - 即您不会获得这些值。因此,您需要添加一个:

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 数组是零索引的。

要打印每个值出现的次数,您需要迭代 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)

关于java - 我怎样才能显示一个数字出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61166854/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com