The Artima Developer Community
Sponsored Link

Java Answers Forum
generate a random number

3 replies on 1 page. Most recent reply: Jul 3, 2012 6:06 AM by Keren Blau

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 3 replies on 1 page
Sarah Jay

Posts: 2
Nickname: new2java12
Registered: Mar, 2012

generate a random number Posted: May 1, 2012 6:28 AM
Reply to this message Reply
Advertisement
please can you help me to write the java code for generating a random number between 7 and 100? thank you for your input, much appreciated :)


Ma Bing

Posts: 2
Nickname: ranger
Registered: Jun, 2012

Re: generate a random number Posted: Jun 25, 2012 3:54 AM
Reply to this message Reply
import java.util.Random;

public class RandomIntGenerator
{
public static void main(String[] args)
{
Random random=new Random();
int i=random.nextInt(994)+7;
System.out.println(i);
}
}

Ma Bing

Posts: 2
Nickname: ranger
Registered: Jun, 2012

Re: generate a random number Posted: Jun 25, 2012 3:55 AM
Reply to this message Reply
sorry
import java.util.Random;

public class RandomIntGenerator
{
public static void main(String[] args)
{
Random random=new Random();
int i=random.nextInt(94)+7;
System.out.println(i);
}
}

Keren Blau

Posts: 11
Nickname: kerenblau8
Registered: Jul, 2012

Re: generate a random number Posted: Jul 3, 2012 6:06 AM
Reply to this message Reply
Hi Sarah,

There two methods I have tried:

1. In the following method the random number received is a float from 0 to, but not including, your max value. In this case you can also receive decimal number (e.g. 2.99999999999).

int min = 7;
int max = 100;

Random r = new Random();
int i1 = r.nextInt(max - min + 1) + min;


2. In the following method you will receive rounded up numbers, giving you a range between 0 and yoir max value inclusive.

Math.floor(Math.random()*100); // 7 - 99
Math.floor(Math.random()*100); // 7 - 99
1 + Math.floor(Math.random()*100); // 7 - 100

randomRange = function(min, max){
return Math.floor(Math.random()*(max-min+1)) + min;
}
randomRange(7,100) // 7-100


Try these out, see which one works best for you.

Cheers, Keren :)

Flat View: This topic has 3 replies on 1 page
Topic: grab frame with JMF Previous Topic   Next Topic Topic: GUI problem - Fields not showing

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use