有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java编写了一个程序,使用1D数组和随机生成器中的值打印出每一个组合被一对骰子掷了多少次

任务的目标是使用并行的一维数组,但也允许使用二维数组

我可以打印出不同的组合,比如一对骰子滚动的1,1(也称为蛇眼)

试图打印出每个组合的滚动次数,而不打印与滚动次数相同的组合是很困难的

例:

输入您想要掷骰子的次数: 五,

你滚了:1和5总共1次-我不想要的

你滚了4次和3次,一共滚了1次

你一共翻滚了2次:1次和5次-对于副本,这就是我想要打印的全部内容

你滚了3次和3次,一共滚了1次

你掷了2次和2次,一共掷了1次

我知道在增加组合数组(保存每个组合的滚动次数)后立即打印出来的循环是不正确的,但我一直在研究如何修改它

我认为COMPO〔0〕〔0〕是1、1、1、1的组合次数〔0〕〔1〕是1、2的次数,等等。p>

import java.util.Scanner;

public class Dice {

Scanner read = new Scanner(System.in);
    Random diceRoll = new Random();
    int numRolls;
    int[] dice1 = new int [1000];
    int[] dice2 = new int [1000];
    int[][] combo = new int[6][6];


public void getRolls() 
{
    System.out.println("Enter the number of times you want to roll a pair of dice: ");
    numRolls = read.nextInt();

    dice1 = new int[numRolls];
    dice2 = new int[numRolls];

    for (int i = 0; i < dice1.length; i++)
    {
        dice1[i] = diceRoll.nextInt(6) + 1;
        dice2[i] = diceRoll.nextInt(6) + 1;
    }

    System.out.println("\n");



    for (int j = 0; j < combo.length; j++)
    {
        for (int k = 0; k < combo[0].length; k++)
        {
            combo[j][k] = 0;
        }
    }

   for (int m = 0; m < numRolls; m++)
    {
        combo[dice1[m] - 1][dice2[m] - 1]++;

        System.out.println("You rolled: " + dice1[m] + " and " + 
        dice2[m] + " a total of " + combo[dice1[m] - 1][dice2[m] - 1] + 
        " times");
    }

共 (2) 个答案

  1. # 1 楼答案

    自我回答:

    我将打印循环与组合计算循环分开。 如果组合的combo值是1,那么我只需打印出来,说明它被滚动了1次。 如果组合的组合值大于1,我会在第一次出现时打印出来,说明它被滚动了那么多次,然后将该组合的组合值设置为0。只打印组合值至少为1的组合,因此无法打印重复行(即1,1滚动4次,现在只打印一行,而不是4行)

        for (int m = 0; m < numRolls; m++)
        {
            combo[dice1[m] - 1][dice2[m] - 1]++;
        }
    
        for (int m = 0; m < numRolls; m++)
        {
            if (combo[dice1[m] - 1][dice2[m] - 1] > 1)
            {
                System.out.println("You rolled: " + dice1[m] + " and " + dice2[m] + " a total of " + combo[dice1[m] - 1][dice2[m] - 1]   + " time(s)");
                combo[dice1[m] - 1][dice2[m] - 1] = 0;
            }
    
            if (combo[dice1[m] - 1][dice2[m] - 1] == 1)
            {
            System.out.println("You rolled: " + dice1[m] + " and " + dice2[m] + " a total of " + combo[dice1[m] - 1][dice2[m] - 1] + " time(s)");
            }
        }
    
  2. # 2 楼答案

    您应该将组合计算循环与打印循环分开。如果订单与你所说的不相关,那应该会给你你想要的正确输出。编码快乐