如何使用Java在一定范围内生成随机数?

时间:2017-06-06 00:32:06

标签: java random

我想在Java中生成一个随机数。它可以是整数,字节或浮点类型,但我真正需要的是生成一个随机数。这就是我正在做的事情:

  1. 生成一定范围内的随机数(例如5到20)。
  2. 取数字并将其存储在变量中。
  3. 对其进行算术运算。
  4. 以下是代码:

    import java.util.HashMap;
    
    public class Attack {
        public static void main(String[] args) {
            HashMap<String, Integer> attacks = new HashMap<String, Integer>();
            attacks.put("Punch", 1);
            attacks.put("Uppercut", 3);
            attacks.put("Roundhouse Kick", 5);
    
            int actionPoints = // Code for random number generation
    
            System.out.println("A brigade integrant appeared!");
            System.out.println("What do you do?");
            System.out.println("1: Punch [1 AP], 2: Uppercut [3 AP], 3: Roundhouse Kick [5 AP]");
            System.out.println("You have " + actionPoints + " Action Points.");
            Scanner reader = new Scanner(System.in);
            System.out.println("Enter a number: ");
            int n = reader.nextInt();
            reader.close();
    
            if n == 1 {
                System.out.println("The brigade integrant takes 2 HP of damage!");
            }
            else if n == 2 {
                System.out.println("The brigade integrant takes 5 HP of damage!");
            }
            else if n == 3 {
                System.out.println("The brigade integrant takes 8 HP of damage!");
            }
        }
    }
    

3 个答案:

答案 0 :(得分:4)

在Java 1.7+中,您可以在one line中执行此操作(不包括import语句;):

import java.util.concurrent.ThreadLocalRandom;

int actionPoints = ThreadLocalRandom.current().nextInt(5, 21); // 5 to 20 inclusive

答案 1 :(得分:1)

试试这个:

int lower = 12;
int higher = 29;

int random = (int)(Math.random() * (higher-lower)) + lower;

答案 2 :(得分:0)

您可以通过多种方式生成随机数。其中两个是:

Math.random(); // Random values ranging from 0 to 1

Random rand; rand.nextInt(x); // Random int ranging from 0 to x

要指定确切的范围,您可以执行以下操作:

int RandomNumber = Min + (int)(Math.random() * Max);