简体   繁体   English

(Java)使用嵌套循环

[英](Java) Using nested loops

My assignment instructions are "rolling" 2 dice and getting the sum and then finding the probability that that sum came up based on how many times the user wants to roll the die. 我的分配指令是“掷出” 2个骰子并获取总和,然后根据用户希望掷出骰子的次数找到该总和的概率。 I must use a nested loop and I can't use separate loops for each dice combination (which I haven't done). 我必须使用嵌套循环,并且不能对每个骰子组合使用单独的循环(尚未完成)。 I am not allowed to use arrays in this assignment. 我不允许在此作业中使用数组。

Write a program to simulate tossing a pair of 11-sided dice and determine the percentage of times each possible combination of the dice is rolled. 编写一个程序来模拟掷一对11面骰子,并确定掷骰子的每种可能组合的次数百分比。

  1. Create a new project called 5.05 Random Dice in the Mod05 Assignments folder. 在Mod05 Assignments文件夹中创建一个名为5.05 Random Dice的新项目。
  2. Create a class called DiceProbability in the newly created project folder. 在新创建的项目文件夹中创建一个名为DiceProbability的类。
  3. Ask the user to input how many times the dice will be rolled. 要求用户输入掷骰子的次数。
  4. Calculate the probability of each combination of dice. 计算每种骰子组合的概率。 (You may want to start with more familiar six-sided dice.) (您可能想从更熟悉的六面骰子开始。)
  5. Print the results neatly in two columns 分两列整齐地打印结果

I need help in finding out what I put into the second "for" loop. 我需要帮助找出我放入第二个“ for”循环中的内容。 Sorry for the messy list of integers and if statements. 对不起,整数列表和if语句比较混乱。 The code is unfinished. 代码未完成。

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

    int count2 = 0;
    int count3 = 0;
    int count4 = 0;
    int count5 = 0;
    int count6 = 0;
    int count7 = 0;
    int count8 = 0;
    int count9 = 0;
    int count10 = 0;
    int count11= 0;
    int count12= 0;
    int count13 = 0;
    int count14 = 0;
    int count15 = 0;
    int count16 = 0;
    int count17 = 0;
    int count18 = 0;
    int count19 = 0;
    int count20 = 0;
    int count21 = 0;
    int count22 = 0;
    int die1 = 0, die2 = 0;
    int rolls = 0;
    int actualDiceSum;
    double probabilityOfDice = 0.0;

    System.out.print("Number of Rolls: ");
    rolls = in.nextInt();

    for(int timesRolled = 0; timesRolled < rolls; timesRolled++)
        {
        die1 = randNum.nextInt(12);
        die2 = randNum.nextInt(12);
        actualDiceSum = die1 + die2;
        for()
        {
            if(actualDiceSum == 2){
            count2++;
            probabilityOfDice = count2 / rolls;
            }
            else if(actualDiceSum == 3){
            count3++;
            probabilityOfDice = count3 / rolls;
            }
            else if(actualDiceSum == 4){
            count4++;
            probabilityOfDice = count4 / rolls;
            }
            else if(actualDiceSum == 5){
            count5++;
            probabilityOfDice = count5 / rolls;
            }
            else if(actualDiceSum == 6){
            count6++;
            probabilityOfDice = count6 / rolls;
            }
            else if(actualDiceSum == 7){
            count7++;
            probabilityOfDice = count7 / rolls;
            }
            else if(actualDiceSum == 8){
            count8++;
            probabilityOfDice = count8 / rolls;
            }
            else if(actualDiceSum == 9){
            count9++;
            probabilityOfDice = count9 / rolls;
            }
            else if(actualDiceSum == 10){
            count10++;
            probabilityOfDice = count10 / rolls;
            }
            else if(actualDiceSum == 11){
            count11++;
            probabilityOfDice = count11 / rolls;
            }
            else if(actualDiceSum == 12){
            count12++;
            probabilityOfDice = count12 / rolls;
            }
            else if(actualDiceSum == 13){
            count13++;
            probabilityOfDice = count13 / rolls;
            }
            else if(actualDiceSum == 14){
            count14++;
            probabilityOfDice = count14 / rolls;
            }
            else if(actualDiceSum == 15){
            count15++;
            probabilityOfDice = count15 / rolls;
            }
            else if(actualDiceSum == 16){
            count16++;
            probabilityOfDice = count16 / rolls;
            }
            else if(actualDiceSum == 17){
            count17++;
            probabilityOfDice = count17 / rolls;
            }
            else if(actualDiceSum == 18){
            count18++;
            probabilityOfDice = count18 / rolls;
            }
            else if(actualDiceSum == 19){
            count19++;
            probabilityOfDice = count19 / rolls;
            }
            else if(actualDiceSum == 20){
            count20++;
            probabilityOfDice = count20 / rolls;
            }
            else if(actualDiceSum == 21){
            count21++;
            probabilityOfDice = count21 / rolls;
            }
            else if(actualDiceSum == 22){
            count22++;
            probabilityOfDice = count22 / rolls;
           }
        }
    }


    System.out.println("Sum of Dice \t\t Probability");
    System.out.println("2's\t\t" + probabilityOfDice + "%");
    System.out.println("3's\t\t" + probabilityOfDice + "%");
    System.out.println("4's\t\t" + probabilityOfDice + "%");
    System.out.println("5's\t\t" + probabilityOfDice + "%");
    System.out.println("6's\t\t" + probabilityOfDice + "%");
    System.out.println("7's\t\t" + probabilityOfDice + "%");
    System.out.println("8's\t\t" + probabilityOfDice + "%");
    System.out.println("9's\t\t" + probabilityOfDice + "%");
    System.out.println("10's\t\t" + probabilityOfDice + "%");
    System.out.println("11's\t\t" + probabilityOfDice + "%");
    System.out.println("12's\t\t" + probabilityOfDice + "%");
    System.out.println("13's\t\t" + probabilityOfDice + "%");
    System.out.println("14's\t\t" + probabilityOfDice + "%");
    System.out.println("15's\t\t" + probabilityOfDice + "%");
    System.out.println("16's\t\t" + probabilityOfDice + "%");
    System.out.println("17's\t\t" + probabilityOfDice + "%");
    System.out.println("18's\t\t" + probabilityOfDice + "%");
    System.out.println("19's\t\t" + probabilityOfDice + "%");
    System.out.println("20's\t\t" + probabilityOfDice + "%");
    System.out.println("21's\t\t" + probabilityOfDice + "%");
    System.out.println("22's\t\t" + probabilityOfDice + "%");
}
}

I think you need to use two dimensional array as below: 我认为您需要使用二维数组,如下所示:

int rolls = 0;
System.out.print("Number of Rolls: ");
rolls = in.nextInt();

int[][] numAndOccuranceCount= new int[11][2]; //sum will be between 2 -12

//initialize your array
for(int indx=0; indx<11;indx++){
   numAndOccuranceCount[indx] = new int[]{indx+2,0);
} 

for(int timesRolled = 0; timesRolled < rolls; timesRolled++){
    die1 = randNum.nextInt(12);
    die2 = randNum.nextInt(12);
    actualDiceSum = die1 + die2;

    for(int indx=0; indx<11;indx++){
       if(actualDiceSum == numAndOccuranceCount[i][0]){
          numAndOccuranceCount[indx][1] = numAndOccuranceCount[indx][1]+1;
          break;
       }
    }
 }

 double proabability = 0.0;
 //compute and print the probablity as below:
  for(int indx=0; indx<11;indx++){
     proabability = numAndOccuranceCount[indx][1]/rolls;
     System.out.println("Probability of "+ numAndOccuranceCount[indx][0] +" = "+proabability);
  }

I have some comment on your code. 我对您的代码有一些评论。

Based on the instruction, you sum up the dice1 and dice2 is not a correct approach 'cause 1 + 5 = 2 + 4 = 3 + 3 but they are different. 根据指令,您总结出dice1和dice2不是正确的方法,因为1 + 5 = 2 + 4 = 3 + 3,但它们是不同的。 So we have to calculate the possibility based on the combination, not the sum. 因此,我们必须根据组合而不是总和来计算可能性。

Here's my code: 这是我的代码:

DTO class: DTO类:

public class DiceCombination {
    private int dice1;
    private int dice2;

    public DiceCombination(int dice1, int dice2) {
        this.dice1 = dice1;
        this.dice2 = dice2;
    }
    /* (non-Javadoc)
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return "Combination of [dice " + dice1 + " and dice " + dice2 + "]";
    }
    /* (non-Javadoc)
     * @see java.lang.Object#hashCode()
     */
    @Override
    public int hashCode() {
    final int prime = 31;
    if(dice1 < dice2) {
        return prime*dice1 + dice2;
    }
    else {
        return prime*dice2 + dice1;
    }
}
    /* (non-Javadoc)
     * @see java.lang.Object#equals(java.lang.Object)
     */
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        DiceCombination other = (DiceCombination) obj;
        if ((dice1 == other.dice1 && dice2 == other.dice2) || (dice1 == other.dice2 && dice2 == other.dice1))
            return true;
        return false;
    }

}

Main class: 主班:

public class Posibility {

 public static void main(String[] args) {
    Map<DiceCombination,Integer> possibility = new HashMap<DiceCombination,Integer>();
    int dice1;
    int dice2;
    int roll = 400; // value here should be inputted from user, you may change any value you want
    Random randNum = new Random();

    for(int i = 0; i < roll; i ++) {
        dice1 = randNum.nextInt(12);
        dice2 = randNum.nextInt(12);
        DiceCombination dc = new DiceCombination(dice1, dice2);
        if(possibility.containsKey(dc)) {
            possibility.put(dc , possibility.get(dc) + 1); 
        }
        else {
            possibility.put(dc, 1);
        }
    }
    for(DiceCombination key : possibility.keySet()) {
        System.out.println("Result: " + key.toString() + " is " + ((double)possibility.get(key)/roll));
    }
 }
}

I agree with @Thinhbk that the question is technically worded in terms of combinations not sums but the picture in the link shows sums so I believe sums is the intention. 我同意@Thinhbk的观点,该问题在技术上用组合而不是总和来表达,但链接中的图片显示总和,因此我认为总和是意图。 The combinations approach as you have coded is impressive but too advanced for what appears to be an intro course to Java. 您编写的组合方法令人印象深刻,但是对于Java入门课程来说太先进了。 I like how the picture shows that the IDE is BlueJ. 我喜欢图片显示IDE是BlueJ的方式。 Takes me back. 带我回来。 Anyway, the assignment description doesn't specify the need for an inner for loop. 无论如何,赋值描述没有指定内部for循环的需要。 I see @user1713336's edit that arrays are not allowed else before your (user1713336's) first loop you could add: 我看到@ user1713336的编辑,即在您可以添加(user1713336)的第一个循环之前,不允许使用其他数组:

int[] count = new int[23];
//0 is the default value for each
//int[22] is the 23rd value in the array

What is your entire inner for loop could be replaced with: 您的整个内部for循环可以替换为:

count[actualDiceSum]++;

Then while printing in a for loop, print count[i]/rolls*100 and start int i at 2, the lowest possible value. 然后在for循环中打印时,打印count[i]/rolls*100并从int i开始,该值应为2,这是最低值。 I suspect you'll learn arrays next so I wanted to show how it'd be done. 我怀疑您接下来将学习数组,因此我想展示如何完成。

Since you can't use arrays, your countx = 0; 由于不能使用数组,因此countx = 0; lines are fine as is. 线条很好。 Don't calculate the probability in real time. 不要实时计算概率。 It's unnecessarily and and adds many lines of code, just keep track of the number of times each value is rolled so: 它是不必要的,并添加了许多行代码,只需跟踪每个值的滚动次数即可,因此:

if(actualDiceSum == 2)
    count2++;
else if(actualDiceSum == 3)
    count3++;
//etc 

Note that you don't need to use {} if only one line of code is tied to the if or while statement as shown. 请注意,如果仅一行代码与if或while语句绑定在一起,则无需使用{} ,如图所示。 Then print the same way as before, count2/rolls*100 (Multiply by 100 since the picture showed percentages, not ratios). 然后以与以前相同的方式进行打印, count2/rolls*100 (乘以100,因为图片显示的是百分比,而不是比率)。

Well according to me you don't require 2nd for loop. 根据我的说法,您不需要第二循环。 Every time a dice is rolled you calculate the the sum and increase the count according to the sum. 每次掷骰子时,您都要计算总和,并根据总和增加计数。

you would require to use separate variables for calculating the probability of each sum. 您将需要使用单独的变量来计算每个和的概率。

For example 例如

Probability of count2 = (count2/number of rolls);
Probability of count3 = (count2/number of rolls);

Use separate variables for probability of counts 将单独的变量用于计数概率

try this code 试试这个代码

import java.util.Random;
import java.util.Scanner;
public class DiceProbability
{
public static void main(String[] args)
{
    Scanner in = new Scanner(System.in);
    Random randNum = new Random();
int count2 = 0;
int count3 = 0;
int count4 = 0;
int count5 = 0;
int count6 = 0;
int count7 = 0;
int count8 = 0;
int count9 = 0;
int count10 = 0;
int count11= 0;
int count12= 0;
int count13 = 0;
int count14 = 0;
int count15 = 0;
int count16 = 0;
int count17 = 0;
int count18 = 0;
int count19 = 0;
int count20 = 0;
int count21 = 0;
int count22 = 0;
int die1 = 0, die2 = 0;
int rolls = 0;
int actualDiceSum;
double probabilityOfDice = 0.0;

System.out.print("Number of Rolls: ");
rolls = in.nextInt();

for(int timesRolled = 0; timesRolled < rolls; timesRolled++)
    {
    die1 = randNum.nextInt(12);
    die2 = randNum.nextInt(12);
    actualDiceSum = die1 + die2;

        if(actualDiceSum == 2){
        count2++;

        }
        else if(actualDiceSum == 3){
        count3++;

        }
        else if(actualDiceSum == 4){
        count4++;

        }
        else if(actualDiceSum == 5){
        count5++;

        }
        else if(actualDiceSum == 6){
        count6++;

        }
        else if(actualDiceSum == 7){
        count7++;

        }
        else if(actualDiceSum == 8){
        count8++;

        }
        else if(actualDiceSum == 9){
        count9++;

        }
        else if(actualDiceSum == 10){
        count10++;

        }
        else if(actualDiceSum == 11){
        count11++;

        }
        else if(actualDiceSum == 12){
        count12++;

        }
        else if(actualDiceSum == 13){
        count13++;

        }
        else if(actualDiceSum == 14){
        count14++;

        }
        else if(actualDiceSum == 15){
        count15++;

        }
        else if(actualDiceSum == 16){
        count16++;

        }
        else if(actualDiceSum == 17){
        count17++;

        }
        else if(actualDiceSum == 18){
        count18++;

        }
        else if(actualDiceSum == 19){
        count19++;

        }
        else if(actualDiceSum == 20){
        count20++;

        }
        else if(actualDiceSum == 21){
        count21++;

        }
        else if(actualDiceSum == 22){
        count22++;

       }
    }
}


System.out.println("Sum of Dice \t\t Probability");
System.out.println("2's\t\t" + count2/rolls + "%");
System.out.println("3's\t\t" + count3/rolls + "%");
System.out.println("4's\t\t" + count4/rolls + "%");
System.out.println("5's\t\t" + count5/rolls + "%");
//and so on...
}
}

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

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