0

I having a little trouble trying to genertae a radom set of numbers with what the user defines as max and min, I am new to programming and feel a little lost with my code

int upperRange; int lowerRange; Random random = new Random(int)(Math.random()*(upperRange - (lowerRange-1)))+lowerRange; Scanner keyboard = new Scanner(System.in); { System.out.println("Enter upper limit number "); upperRange = keyboard.nextInt(); System.out.println("Enter lower limit number"); lowerRange = keyboard.nextInt(); 

Any help would be appreciated

1
  • why is there that curly bracket thing? {, show us whole void (function)CommentedJul 7, 2011 at 22:12

3 Answers 3

4

Where r is an instance of class Random, and x and y are positive integers,

r.nextInt(y - x) + x 

should do what you want. It will give you an integer in the range x (inclusive) to y (exclusive).

3
  • Yes, it will ask the user to define the max/min range for a number guessing game
    – pbj
    CommentedJul 7, 2011 at 22:15
  • Good to know, sounds like you need integers only. Just FYI the answer above assumes x and y are positive and x <= y. Also, I should mention if the maximum bound is a legal guess, you'll need r.nextInt(y - x + 1), but do be careful of the case in which y is Integer.MAX_VALUE and x is 0.
    – Ray Toal
    CommentedJul 7, 2011 at 22:20
  • Import java.util.Random, declare r as Random r = new Random(), and make sure x and y are declared as ints.
    – Ray Toal
    CommentedJul 7, 2011 at 22:21
1

Try this:

public class TestRandomBounds { public static void main(String[] args) { int upperBound = 100; int lowerBound = 50; Random random = new Random(); System.out.println(lowerBound + random.nextInt(upperBound - lowerBound)); } } 

Once the random bounds are defined you just need to generate a random number that will reside inside those bounds.

    0

    Your code could be written like this:

    import java.util.*; public class RandGuess { public static void main ( String[] args ) { int upperRange; int lowerRange; Random random; int randomFromUserLimits; Scanner keyboard = new Scanner(System.in); System.out.print("Enter upper limit number: "); upperRange = keyboard.nextInt(); System.out.print("Enter lower limit number: "); lowerRange = keyboard.nextInt(); random = new Random(); randomFromUserLimits = random.nextInt(upperRange-lowerRange) + lowerRange; System.out.println("A random number between " + lowerRange + " and " + upperRange + " = " + randomFromUserLimits); } } 

      Start asking to get answers

      Find the answer to your question by asking.

      Ask question

      Explore related questions

      See similar questions with these tags.