【问题标题】:How to add together numbers from a random number generator如何将随机数生成器中的数字相加
【发布时间】:2021-03-02 15:04:13
【问题描述】:

我正在为学校制作一个随机数生成器,我必须将总数加在一起,但问题是我使用了一个循环,所以我实际上并没有将随机生成的数字存储在任何地方,所以我不太确定什么如何创建一个总。就像随机数生成器的结果是 3 和 3,总数会告诉你它是 6。这是我的代码:

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

public class Assignment7 {

    public static void main(String[] args) {

        Scanner key = new Scanner(System.in);
        Random rand = new Random();
        
        int randomNumber = 0;
        
        System.out.println("Welcome to randomdiceroll.com or something!"
                         + "\nPlease enter how many dice you'd like to roll.");
        int amount = key.nextInt();
        
        System.out.println("Please enter the range for the di(c)e from 1-?");
        int limit = key.nextInt();
        
        for(int i = 0; i < amount; i++) {
            randomNumber = rand.nextInt(limit) +1;
            System.out.println(randomNumber);
        }
        
        int total; //The part I cant figure out
        
        System.out.println("\nYour total is..." + total + ".");
        
        key.close();
    }
}

请原谅可怕的格式,我试过了:

randomNumber * amount

但这显然行不通。我正在使用 Java 如果我解释了这个奇怪的问题,我可以肯定地澄清!我确信答案非常简单,但我是初学者,很遗憾不知道。

提前谢谢你!

【问题讨论】:

    标签: java eclipse


    【解决方案1】:

    您可以在循环中添加随机数。

    int total=0;
    for(int i=0; i<amount; i++){
        int randomNumber = rand.nextInt(limit) +1;
        total += randomNumber;
        System.out.println(randomNumber);
    }
    

    【讨论】:

      【解决方案2】:

      在 for 循环之前定义总数,每次将随机数添加到总数中。
      我会这样做:

      import java.util.Scanner;
      import java.util.Random;
      
      public class Assignment7 {
        public static void main(String[] args) {
          Scanner key = new Scanner(System.in);
          Random rand = new Random();
          System.out.println("Welcome to randomdiceroll.com or something!"
                               + "\nPlease enter how many dice you'd like to roll.");
          int amount = key.nextInt();
              
          System.out.println("Please enter the range for the di(c)e from 1-?");
          int limit = key.nextInt();
          int total = 0;
          for(int i = 0; i < amount; i++) {
            randomNumber = rand.nextInt(limit) +1;
            total += randomNumber;
            System.out.println(randomNumber);
          }
          System.out.println("\nYour total is..." + total + ".");
          key.close()
        }
      }
      

      【讨论】:

      • 这很好用!非常感谢你帮了大忙!
      猜你喜欢
      • 1970-01-01
      • 2021-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多