简体   繁体   English

我用什么来跟踪一个数字?

[英]What do I use to keep track of a number?

import java.util.Random;
import java.util.Scanner;

public class dieClass
{
    public static void main(String []args)
    {
        Random gen = new Random();
        Scanner reader = new Scanner(System.in);


        System.out.println("How many times do you want to roll?");
        int rollamt = reader.nextInt();



        for (int i = 0; i < rollamt; i++)
        {
            int dice1 = gen.nextInt(6) + 1;
            int dice2 = gen.nextInt(6) + 1; 
            int total = dice1 + dice2;
            int [] arrayDice = new int [rollamt];

            for (int r = 0; r < arrayDice.length; r++)
            {
                arrayDice[r] = total;
            }

          System.out.println("sum is " + total);
        }
    }
}

I was on to something but I give up.我正在做某事,但我放弃了。 How do i keep track of how many times the sum of the two die was chosen?我如何跟踪选择了两个骰子的总和的次数? A while loop ?一个while循环? (The result of the two die can only be between 2 and 12) (两个骰子的结果只能在2到12之间)

So for example I want to have a loop that will Add one to its counter for its assigned number因此,例如我想要一个循环,它将为其分配的编号添加一个到其计数器

x = sum of two die x = 两个骰子的总和

y = number of times y = 次数

The output can be "the number x was rolled y times"输出可以是“数字 x 被滚动 y 次”

Inside of your while loop, you simply have another array that holds a count of each possible roll.在你的 while 循环中,你只是有另一个数组来保存每个可能滚动的计数。

You've already got the total, right here.你已经得到了总数,就在这里。

int total = dice1 + dice2;

Just add an array, outside of the loop to start a count:只需在循环外添加一个数组即可开始计数:

int possibleRolls[]=new int[13]

and inside your loop:在你的循环中:

possibleRolls[total]++;

When the loop is finished, you can check the indexes in the array to see how many each total was rolled.循环完成后,您可以检查数组中的索引以查看每个总计滚动了多少。

You can create a Map that is a Map of the number to the number of times rolled.您可以创建一个地图,该地图是数量到滚动次数的地图。

java.util.Map<Integer, Integer> rollMap = new java.util.HashMap<Integer, Integer>();
for (int i = 0; i < rollamt; i++)
{
    int dice1 = gen.nextInt(6) + 1;
    int dice2 = gen.nextInt(6) + 1; 
    int total = dice1 + dice2;

    Integer count = rollMap.get(total);
    if (null == count)
    {
        rollMap.put(total, Integer.valueOf(1));
    }
    else
    {
        rollMap.put(total, Integer.valueOf(count + 1));
    }
}

for (Map.Entry<Integer, Integer> entry : rollMap.entrySet())
{
    System.out.println("Number " + entry.getKey()+ " was rolled " + entry.getValue() + "times")
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM