我正在尝试创建一个程序,要求用户输入要滚动的6面骰子的数量,然后输入他们想要运行的卷数(试验)。在代码的最后,它应该向用户显示可能的每个数字中有多少以及是否存在条纹(如果有的话应该说条纹是什么以及它开始的卷号。
为了保持简单到目前为止,我的程序应该只询问使用两个6面骰子进行多少次试验,并显示上面列出的显示。
问题是显示器没有显示我的数学应该允许的百分比,当涉及到条纹时我不知道如何说明它开始的哪个试验以及条纹上的数字....非常感谢帮助。
import java.util.*;
公共类RollThoseDice {
public static void main(String[] args) {
//start of method
//variables needed for program
int total;
int newStreak = 1;
int streak = 1;
int totalIs2 = 0;
int totalIs3 = 0;
int totalIs4 = 0;
int totalIs5 = 0;
int totalIs6 = 0;
int totalIs7 = 0;
int totalIs8 = 0;
int totalIs9 = 0;
int totalIs10 = 0;
int totalIs11 = 0;
int totalIs12 = 0;
double twoPercent = 0;
double threePercent = 0;
double fourPercent = 0;
double fivePercent = 0;
double sixPercent = 0;
double sevenPercent = 0;
double eightPercent = 0;
double ninePercent = 0;
double tenPercent = 0;
double elevenPercent = 0;
double twelvePercent = 0;
//intro to program and purpose
System.out.println("Today we are going to generate 2 random dice and tally the results of their random combined rolls");
System.out.println("At the bottom of the results, the longest streak will also be listed");
//variable for while loop
boolean validInput = true;
//declaration of scanner before try/catch
Scanner userInput = new Scanner(System.in);
//test for valid input
while (validInput){
try {
System.out.print(" \n" + "Please enter the number of trials you would like to be performed:");
int numberOfRolls = Integer.parseInt(userInput.nextLine());
//Stop from calling for anything else
userInput.close();
//declaring of variables for die 1 and die 2
int die1[] = new int[numberOfRolls];
int die2[] = new int[numberOfRolls];
//create an array for each die roll so that they can each be saved for recalling streak
int[] array = new int[numberOfRolls];
for (int i=1; i<array.length; i++ ) {
die1[i] = (int) ((Math.random() * 6) + 1);
die2[i] = (int) ((Math.random() * 6) + 1);
total = die1[i] + die2[i];
//streak checker
int lastTotal = die1[i-1] + die2[i-1];
if (lastTotal == total) {
streak++;
if (streak > newStreak) {
newStreak = streak;
}
} else {
streak = 1;
}
//count total of each numbered possibility rolled
if (total == 2) {
totalIs2++;
}
if (total == 3) {
totalIs3++;
}
if (total == 4) {
totalIs4++;
}
if (total == 5) {
totalIs5++;
}
if (total == 6) {
totalIs6++;
}
if (total == 7) {
totalIs7++;
}
if (total == 8) {
totalIs8++;
}
if (total == 9) {
totalIs9++;
}
if (total == 10) {
totalIs10++;
}
if (total == 11) {
totalIs11++;
}
if (total == 12) {
totalIs12++;
//calculate percent of each number rolled
twoPercent = (totalIs2 / numberOfRolls);
threePercent = (totalIs3 / numberOfRolls);
fourPercent = (totalIs4 / numberOfRolls);
fivePercent = (totalIs5 / numberOfRolls);
sixPercent = (totalIs6 / numberOfRolls);
sevenPercent = (totalIs7 / numberOfRolls);
eightPercent = (totalIs8 / numberOfRolls);
ninePercent = (totalIs9 / numberOfRolls);
tenPercent = (totalIs10 / numberOfRolls);
elevenPercent = (totalIs11 / numberOfRolls);
twelvePercent = (totalIs12 / numberOfRolls);
}
}
//results
System.out.println("\n" + "Total Results:");
System.out.println("\n" + "Total 2 happened " + totalIs2 + " times which is " + twoPercent + "%");
System.out.println("Total 3 happened " + totalIs3 + " times which is " + threePercent + "%");
System.out.println("Total 4 happened " + totalIs4 + " times which is " + fourPercent + "%");
System.out.println("Total 5 happened " + totalIs5 + " times which is " + fivePercent + "%");
System.out.println("Total 6 happened " + totalIs6 + " times which is " + sixPercent + "%");
System.out.println("Total 7 happened " + totalIs7 + " times which is " + sevenPercent + "%");
System.out.println("Total 8 happened " + totalIs8 + " times which is " + eightPercent + "%");
System.out.println("Total 9 happened " + totalIs9 + " times which is " + ninePercent + "%");
System.out.println("Total 10 happened " + totalIs10 + " times which is " + tenPercent + "%");
System.out.println("Total 11 happened " + totalIs11 + " times which is " + elevenPercent + "%");
System.out.println("Total 12 happened " + totalIs12 + " times which is " + twelvePercent + "%");
System.out.println("The longest run was a run of " + newStreak + " *number that was on a streak*" + " that began at roll" + "*where it started*");
//stop the loop
validInput = false;
}
//catch exception and call for new input
catch(Exception e){
System.out.println("\n" + "Your input was not a number. Please try again: ");
}
}
}
答案 0 :(得分:0)
您应该在//calculate percent of each number rolled
之前移动//results
计算。请注意,您将其放在if (total == 12)
内。它应该是percents[i] = (total[i] * 100 / numberOfRolls);
下次你要写下这样的内容:
int totalIs2 = 0;
int totalIs3 = 0;
...
你应该使用数组
你可以写一个for循环而不是线性重复代码
即。你可以替换:
//calculate percent of each number rolled
twoPercent = (totalIs2 / numberOfRolls);
...
和
System.out.println("\n" + "Total 2 happened " + totalIs2 + " times which is " + twoPercent + "%");
...
与
for (int i = 2; i < totalCount.length; i++) {
double percent = totalCount[i] * 100/ numberOfRolls;
System.out.println("\n" + "Total " + i + " happened " + totalCount[i] + " times which is " + percent + "%");
}
以下是整个计划:
public class RollThoseDices {
private int lastTotal;
private int streak;
private int longestStreak;
private int startOfTheLongestStreak;
private int[] totalCount = new int[13];
RollThoseDices(int numberOfRolls) {
run(numberOfRolls);
}
public void run(int numberOfRolls) {
for (int i=0; i<numberOfRolls; i++ ) {
int die1 = (int) ((Math.random() * 6) + 1);
int die2 = (int) ((Math.random() * 6) + 1);
int total = die1 + die2;
totalCount[total]++;
if (lastTotal == total) {
streak++;
if (streak > longestStreak) {
longestStreak = streak;
startOfTheLongestStreak = i - longestStreak;
}
} else {
streak = 1;
}
lastTotal = total;
}
}
private static int readInt(Scanner scanner) {
System.out.print(" \n" + "Please enter the number of trials you would like to be performed:");
while (!scanner.hasNextInt()) {
scanner.next();
System.out.println("\n" + "Your input was not a number. Please try again: ");
}
return scanner.nextInt();
}
public static void main(String[] args) {
//intro to program and purpose
System.out.println("Today we are going to generate 2 random dice and tally the results of their random combined rolls");
System.out.println("At the bottom of the results, the longest streak will also be listed");
// read number of rolls
int numberOfRolls = 0;
try(Scanner userInput = new Scanner(System.in)) {
numberOfRolls = readInt(userInput);
}
RollThoseDices results = new RollThoseDices(numberOfRolls);
//results
System.out.println("\n" + "Total Results:");
System.out.println("The longest run was a run of " + results.longestStreak + " that began at roll " + results.startOfTheLongestStreak);
for (int i = 2; i < results.totalCount.length; i++) {
double percent = (results.totalCount[i] * 100.0) / numberOfRolls;
System.out.println("\n" + "Total " + i + " happened " + results.totalCount[i] + " times which is " + percent + "%");
}
}
}
答案 1 :(得分:0)
正如lifus的第一个回答中提到的,使用数组。此外,条纹和它开始的试验可以很容易地存储。将开头存储为
start = current_trial_no - current_longest_streak
。这意味着您对变量的赋值将进入存储最长条纹值的部分。
import java.util.*;
import java.lang.*;
import java.io.*;
import java.text.DecimalFormat;
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner cin = new Scanner(System.in);
boolean run = true ;
int[] sum = new int[13] ;
float[] percent = new float[13];
int streak = 0, streakValue = 0, currentStreak = 0, streakStart = 0, trials = 0 ;
int dice1 = 0, dice2 = 0 ;
for(int i = 0; i < sum.length; ++i)
{
sum[i] = 0 ;
percent[i] = 0.0f;
}
do
{
trials = cin.nextInt();
int prevSum = 0 ;
for(int t = 0; t < trials; ++t)
{
dice1 = (int) ((Math.random() * 6) + 1);
dice2 = (int) ((Math.random() * 6) + 1);
sum[dice1 + dice2]++ ;
if((dice1 + dice2) == prevSum)
{
++currentStreak ;
streakValue = prevSum ;
if(currentStreak > streak)
{
streak = currentStreak ;
streakStart = t - streak ;
}
}
else {
currentStreak = 1 ;
}
prevSum = dice1 + dice2 ;
}
System.out.println("Continue ? (y/n) : ");
run = cin.nextLine().equals("y");
} while(run);
DecimalFormat df = new DecimalFormat("###.##");
// Start from 2 - the minimum sum possible.
for(int i = 2; i < 13; ++i)
{
percent[i] = (float)sum[i] / (float)trials * 100.0f ;
System.out.println("The sum " + i + " has occurred " + df.format(percent[i]) + "% of times");
}
System.out.println("Longest streak of " + streakValue + " has occurred for " + streak + " times");
System.out.println("It started at : " + streakStart);
}
}
注意循环内if
条件的内部。 Here是同一版本的工作版本。
答案 2 :(得分:0)
看起来您已经获得了使用Arrays的直接建议。正如其他人已经证明的那样,这显着缩短了输入内容时的代码行和重复性。 我要强调的另一件事是编程时尝试更抽象地思考。将功能分解为更小的更容易的块。有时候在考虑整个情况时,它会变得有点消耗并且很难处理。例如,这在实践中对于这个骰子卷的意义可能是首先制作一个代表骰子的类,例如;
public class Dice
{
//declare values
Public Dice()
{
//initialise values
}
public int rollDice(int times)
{
// some code here
]
public int countStreaks()
{
// some code here
}
}
显然上面的代码只是一个简单的例子,但重点是上面的类将为您提供构建程序其余部分所需的所有基本骰子函数。然后,您的入口点可以只使用此类来执行您想要的功能。 您应该发现以这种方式编程可以带来许多好处,而不仅限于提高工作效率,并且当您希望返回并添加功能或扩展原始程序超出其原始范围时,可以更轻松地使用它。 将此与您在上面学到的内容一起使用Arrays,看看你如何继续。完成后我会建议您将新代码与旧代码进行比较以查看差异。
希望有所帮助,
此致 V
答案 3 :(得分:0)
import javax.swing.*;
import java.util。*;
公共类RollThoseDice {
public static void main(String[] args) {
//start of method
//variables needed for program
int total;
int newStreak = 1;
int streak = 1;
int totalIs2 = 0;
int totalIs3 = 0;
int totalIs4 = 0;
int totalIs5 = 0;
int totalIs6 = 0;
int totalIs7 = 0;
int totalIs8 = 0;
int totalIs9 = 0;
int totalIs10 = 0;
int totalIs11 = 0;
int totalIs12 = 0;
double twoPercent;
double threePercent;
double fourPercent;
double fivePercent;
double sixPercent;
double sevenPercent;
double eightPercent;
double ninePercent;
double tenPercent;
double elevenPercent;
double twelvePercent;
//intro to program and purpose
System.out.println("Today we are going to generate 2 random dice and tally the results of their random combined rolls");
System.out.println("At the bottom of the results, the longest streak will also be listed");
//variable for while loop
boolean validInput = true;
//declaration of scanner before try/catch
Scanner userInput = new Scanner(System.in);
//test for valid input
while (validInput){
try {
int numberOfRolls = Integer.parseInt(JOptionPane.showInputDialog("Please Enter the number of trials you would like to be performed: "));
//Stop from calling for anything else
userInput.close();
//declaring of variables for die 1 and die 2
int die1[] = new int[numberOfRolls];
int die2[] = new int[numberOfRolls];
//create an array for each die roll so that they can each be saved for recalling streak
int[] array = new int[numberOfRolls];
for (int i=1; i<array.length; i++ ) {
die1[i] = (int) ((Math.random() * 6) + 1);
die2[i] = (int) ((Math.random() * 6) + 1);
total = die1[i] + die2[i];
//streak checker
int lastTotal = die1[i-1] + die2[i-1];
if (lastTotal == total) {
streak++;
if (streak > newStreak) {
newStreak = streak;
/* // Find-Max variant -- rather than finding the max value, find the
// *index* of the max value
public int findMaxIndex(int[] nums) {
int maxIndex = 0; // say the 0th element is the biggest
int maxValue = nums[0];
// Look at every element, starting at 1
for (int i=1; i<nums.length; i++) {
if (nums[i] > maxValue) {
maxIndex = i;
maxValue = nums[maxIndex];
}
}
return maxIndex;
}
*/
}
} else {
streak = 1;
}
//count total of each numbered possibility rolled
if (total == 2) {
totalIs2++;
}
if (total == 3) {
totalIs3++;
}
if (total == 4) {
totalIs4++;
}
if (total == 5) {
totalIs5++;
}
if (total == 6) {
totalIs6++;
}
if (total == 7) {
totalIs7++;
}
if (total == 8) {
totalIs8++;
}
if (total == 9) {
totalIs9++;
}
if (total == 10) {
totalIs10++;
}
if (total == 11) {
totalIs11++;
}
if (total == 12) {
totalIs12++;
}
}
//Apply decimal place rounder in order to get percentages rounded to 2 places
//calculate percent of each number rolled
twoPercent = (totalIs2 / (double) numberOfRolls) * 100;
threePercent = (totalIs3 / (double) numberOfRolls) * 100;
fourPercent = (totalIs4 / (double) numberOfRolls) * 100;
fivePercent = (totalIs5 / (double) numberOfRolls) * 100;
sixPercent = (totalIs6 / (double) numberOfRolls) * 100;
sevenPercent = (totalIs7 / (double) numberOfRolls) * 100;
eightPercent = (totalIs8 / (double) numberOfRolls) * 100;
ninePercent = (totalIs9 / (double) numberOfRolls) * 100;
tenPercent = (totalIs10 / (double) numberOfRolls) * 100;
elevenPercent = (totalIs11 / (double) numberOfRolls) * 100;
twelvePercent = (totalIs12 / (double) numberOfRolls) * 100;
//results
System.out.println("\n" + "Total Results:");
System.out.println("\n" + "Total 2 happened " + totalIs2 + " times which is " + twoPercent + "%");
System.out.println("Total 3 happened " + totalIs3 + " times which is " + threePercent + "%");
System.out.println("Total 4 happened " + totalIs4 + " times which is " + fourPercent + "%");
System.out.println("Total 5 happened " + totalIs5 + " times which is " + fivePercent + "%");
System.out.println("Total 6 happened " + totalIs6 + " times which is " + sixPercent + "%");
System.out.println("Total 7 happened " + totalIs7 + " times which is " + sevenPercent + "%");
System.out.println("Total 8 happened " + totalIs8 + " times which is " + eightPercent + "%");
System.out.println("Total 9 happened " + totalIs9 + " times which is " + ninePercent + "%");
System.out.println("Total 10 happened " + totalIs10 + " times which is " + tenPercent + "%");
System.out.println("Total 11 happened " + totalIs11 + " times which is " + elevenPercent + "%");
System.out.println("Total 12 happened " + totalIs12 + " times which is " + twelvePercent + "%");
System.out.println("The longest run was a run of " + newStreak + " *number that was on a streak*" + " that began at roll" + "*where it started*");
//stop the loop
validInput = false;
}
//catch exception and call for new input
catch(Exception e){
System.out.println("\n" + "Your input was not a number. Please try again: ");
}
}
}
}
答案 4 :(得分:0)
import java.text.DecimalFormat; import java.util。*; //导入实用程序
公共类RollThoseDice {
//private variables for use in code
private int firstRoll; //initial total to compare with next to scan for streaks
private int streak; //streak
private int longestStreak; //longest streak if more than 1
private int beginningOfLongestStreak; //where in the code the longest streak started for display
private int[] combineTotal = new int[13]; //total of 2 randomly rolled 6-sided dice
RollThoseDice(int numberOfRolls) {
run(numberOfRolls);
}
public void run(int numberOfRolls) {
for (int i=0; i<numberOfRolls; i++ ) {
int die1 = (int) ((Math.random() * 6) + 1); //random number between 1-6
int die2 = (int) ((Math.random() * 6) + 1);
int total = die1 + die2; //math for total
combineTotal[total]++; //adding totals to the array
if (firstRoll == total) { //comparing 2 rolls in order to see if there is a streak or not
streak++;
if (streak > longestStreak) { //comparing new streak to old streak to pick the larger of 2
longestStreak = streak;
beginningOfLongestStreak = i - longestStreak; //getting to the beginning of the streak in order to display to user
}
} else {
streak = 1;
}
firstRoll = total;
}
}
private static int readInt(Scanner scanner) {
System.out.print(" \n" + "Please enter the number of trials you would like to be performed: "); //prompt user for number of trials (int only)
while (!scanner.hasNextInt()) {
scanner.next();
System.out.println("\n" + "Your input was not a number. Please try again: "); //drop garbage input
}
return scanner.nextInt(); //return good input
}
public static void main(String[] args) {
//intro to program and purpose
System.out.println("Today we are going to generate 2 random dice and tally the results of their random combined rolls");
System.out.println("At the bottom of the results, the longest streak will also be listed");
// read number of rolls
int numberOfRolls = 0; //casting the number of rolls as 0 initially
try(Scanner userInput = new Scanner(System.in)) {
numberOfRolls = readInt(userInput); //declaring that the above good input is variable number of rolls
}
RollThoseDice results = new RollThoseDice(numberOfRolls);
DecimalFormat df = new DecimalFormat("###,##0.00"); //round the decimal values
//results
System.out.println("\n" + "Total Results:");
for (int i = 2; i < results.combineTotal.length; i++) {
double percent = (results.combineTotal[i] * 100.0) / numberOfRolls;
System.out.println("Total " + i + " happened " + results.combineTotal[i] + " times which is " + df.format(percent) + "%"); //display rolls info
}
System.out.println("\n" +"The longest run was a run of " + results.longestStreak + " that began at roll " + results.beginningOfLongestStreak); //display streak info
}
}