Search code examples
javadice

How to ask user for number of times to roll a 6 sided dice?


How do I ask a user how many 6 sided dice to roll to add them to their given offset?

I have one 6 sided die rolling and being added to the given offset but need to add user input D6s.

import java.util.*;
import java.lang.Math;

public class Fun

{
    public static void main(String[] args) {

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



      System.out.print("How many dice do you want to roll?");
      int D6 = scan.nextInt();


      System.out.print("What would you like your offset to be?");
      int offset = scan.nextInt();

      int roll= rand.nextInt(6)+1;
      int total= roll+offset;

      System.out.print("The result of rolling "+D6+"D6+"+offset+" is "       +total);

}
}

Solution

  • You can write a simple for loop which iterates D6 number of times and adds up the numbers, e.g.:

    public static void main(String[] args) {
    
        Scanner scan = new Scanner(System.in);
        Random rand = new Random();
    
        System.out.print("How many dice do you want to roll?");
        int D6 = scan.nextInt();
    
        System.out.print("What would you like your offset to be?");
        int offset = scan.nextInt();
    
        int total = 0;
    
        for(int i=0 ; i<D6 ; i++){
            int number = rand.nextInt(6) + 1;
            System.out.println("Rolled " + number);
            total += number;
        }
    
        total = total + offset;
    
        System.out.print("The result of rolling " + D6 + "D6+" + offset + " is " + total);
    
    }