有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何询问用户掷6面骰子的次数?

如何询问用户要掷多少个6面骰子才能将其添加到给定的偏移量

我有一个6面模具滚动,并被添加到给定的偏移量,但需要添加用户输入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);

}
}

共 (3) 个答案

  1. # 1 楼答案

    您可以通过for循环多次掷骰子:

    import java.util.*;
    import java.lang.Math;
    
    public class Felcan_A02Q3{
    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 = offset; //the value of total is set to the same as offset
      for(int x = 0; x < D6; x++){ //this loop repeats as often as the value of D6 is
        total =+ rand.nextInt(6)+1; //here every roll of the dice is added to the total value
      }
    
      System.out.print("The result of rolling "+D6+"D6+"+offset+" is "       +total);
    
    }
    }
    

    这就是它应用于代码的方式

  2. # 2 楼答案

    您可以编写一个简单的for循环,该循环迭代D6次并将数字相加,例如:

    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);
    
    }
    
  3. # 3 楼答案

    您已经询问用户希望滚动多少次,此时您可以使用for循环:

    System.out.print("How many dice do you want to roll?");
    int D6 = scan.nextInt();
    for (int i = 0; i < D6; i++) { //This will roll the specified amount of times
        //Rest of code here
    }