-1

I want to generate a random number in Java. It can be of integer, byte or float type, but all I really need it is to generate a random number. This is what I'm doing:

  1. Generate a random number within a certain range (e.g. 5 through 20).
  2. Take the number and store it within a variable.
  3. Perform arithmetic on it.

Here's the code:

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!");
        }
    }
}
  • [Have](https://stackoverflow.com/questions/363681/how-do-i-generate-random-integers-within-a-specific-range-in-java) - [you](https://stackoverflow.com/questions/363681/how-do-i-generate-random-integers-within-a-specific-range-in-java) - [Googled](https://stackoverflow.com/questions/20389890/generating-a-random-number-between-1-and-10-java) - [anything](https://docs.oracle.com/javase/7/docs/api/java/util/Random.html)? – Matt Clark Jun 06 '17 at 00:38

3 Answers3

4

In Java 1.7+ you can do it in one line (not counting the import statement ;):

import java.util.concurrent.ThreadLocalRandom;

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

Try this :

int lower = 12;
int higher = 29;

int random = (int)(Math.random() * (higher-lower)) + lower;
Simo
  • 195
  • 1
  • 16
0

There are multiple options for you to generate a random number. Two of these would be:

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

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

To specify the exact range you could do something like this:

int RandomNumber = Min + (int)(Math.random() * Max); 
Shiro
  • 2,610
  • 2
  • 20
  • 36