[英]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.