1
\$\begingroup\$

The algorithm bellow is meant to allow a user to roll a die as many times as he would like, then print how many times each side was rolled and how many rolls there were total.

    import java.util.Random;
import java.util.Scanner;

public class DieRoll {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        int roll;
        int totalRolls = 0;
        int roll1 = 0;
        int roll2 = 0;
        int roll3 = 0;
        int roll4 = 0;
        int roll5 = 0;
        int roll6 = 0;
        int numberOfRolls;

        Scanner scan = new Scanner(System.in);
        Random generator = new Random();

        System.out.println("How many times would you like to roll? ");
        numberOfRolls = scan.nextInt();

    for (int numberOfLoops = numberOfRolls; numberOfLoops>0; numberOfLoops--) {

        roll = generator.nextInt(6) + 1;
        System.out.println("your roll was: " + roll);

        switch (roll) {
            case 1:
                roll1 = roll1 + 1;
                break;
            case 2:
                roll2 = roll2 + 1;
                break;
            case 3:
                roll3 = roll3 + 1;
                break;
            case 4:
                roll4 = roll4 + 1;
                break;
            case 5:
                roll5 = roll5 + 1;
                break;
            case 6:
                roll6 = roll6 + 1;
                break;
                default:
                    break;
            }
        }
        System.out.println("\nyou rolled a 1: " + roll1);
        System.out.println("you rolled a 2: " + roll2);
        System.out.println("you rolled a 3: " + roll3);
        System.out.println("you rolled a 4: " + roll4);
        System.out.println("you rolled a 5: " + roll5);
        System.out.println("you rolled a 6: " + roll6);

        System.out.println("\nYou spun a total of : " + numberOfRolls);
    }
}
\$\endgroup\$
1
\$\begingroup\$

The algorithm can be simplified quite a bit. No need for switch-case. Just create an array (faceCount) with six slots and increment the appropriate slot. In other words:

roll = generator.nextInt(6);
faceCount[roll]++;

Then to print, iterate over faceCount and display the appropriate values (increment by one to adjust for array indexing).

\$\endgroup\$

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.