繁体   English   中英

基本的Java Dice程序-找不到最长的条纹

[英]Basic Java Dice program - trouble finding longest streak

我目前正在研究一个基本的(正如我所看到的,经常分配的)java项目,在该项目中我将创建一个模拟骰子滚动的程序。 在我的项目中,我仅模拟两个六个侧面模具的滚动。 在完成此任务时需要使用阵列。

到目前为止,我有try / catch块,该块向用户询问他们要模拟的掷骰数量,并确保他们给出整数输入。 反过来,这会为骰子模拟器创建数组的长度。 至此,我的代码可以正常工作了,但是现在我仍然停留在如何找到该数组中最长的连续求和条纹上。

我非常确定我需要将每个掷骰子的dieSum值与其自身进行比较,如果dieSum == dieSum,然后将当前条纹的变量增加1。我不确定如何执行此操作,我怀疑可能有问题,因为我的dieSum变量未存储到数组中。

import java.util.Scanner;
public class RollThoseDice {
public static void main(String[] args) {
    Scanner kbd = new Scanner(System.in);

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

    //Variable listing and initialization
    int rollTotal = 0; //number of trials
    int dieSum; //sum of the outcome of both dice per roll

    //Try - Catch block to ensure positive integer input from user for rollTotal
    System.out.println("***Welcome to the Dice Roll Probability Generator***");
    while (true){
        System.out.println("Enter how many dice rolls you would like to simulate: ");
        try {
            rollTotal = kbd.nextInt() + 1;
            break;
        } catch (Exception e) {
            System.out.println("Please only enter a positive integer. Try again. ");
            kbd.next();

        }
    }


    int die1[] = new int[rollTotal]; //Variable for the first die
    int die2[] = new int[rollTotal]; //Variable for the second die


    int[] diceArray = new int[rollTotal];   
    for (int i=1; i<diceArray.length; i++ ) {
        die1[i] = (int)(6.0*Math.random() + 1.0); //Generate random # between 1-6
        die2[i] = (int)(6.0*Math.random() + 1.0);
        System.out.println("***Roll " + i + "***");
        System.out.print("Dice one rolled: " + die1[i] + ", dice two rolled: " + die2[i] + "\n") ;
        dieSum = die1[i] + die2[i];
        System.out.println("Total rolled was: " + dieSum + "\n");

    }
}

}

非常感谢您为我做的这件事,并为我的现场和编程总体上感到新鲜。

您需要跟踪另外两个变量: int biggestStreak, currentStreak (以1初始化)。

掷骰子并存储变量后,可以检查掷骰是否与之前掷骰相同,并增加currentStreak

int lastDieSum = die1[i-1] + die2[i-1];

if (lastDieSum == dieSum) {
     currentStreak++;
     if (currentStreak > biggestStreak) {
         biggestStreak = currentStreak;
     } 
} else {
     currentStreak = 1;
}

如果最后的条纹大于最大的条纹,则最后一位现在还将当前的条纹存储在biggestStreak 最后,当值不再与lastDieSum同时,将当前条纹设置回零。

我希望这有帮助!

一种非常简单的解决方案是在代码中再创建两个变量。

一个保留当前条纹,另一个保留先前的dieSum。

每次完成滚动时,都要运行一个if语句,将当前dieSum与以前的dieSum进行比较,如果它们相等,则增加条纹,否则将条纹重新设置为0。

暂无
暂无

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

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