Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

true randomInt

Status
Not open for further replies.

m3the01

Technical User
Feb 21, 2002
41
CA
just wondering how you could produce a true random in, here is my code. Only thing is that everythime the random int is in the same order, first time 73 second time 10 and so on everytime i run my program






public class GuessingGame{

private RandomInt generator;
private int genNumber;
private IntValidator test;
private int uservalue;
private int guessCounter;


public GuessingGame(){

generator = new RandomInt(1);
genNumber = generator.next(99);


}

public void play(){

test = new IntValidator("Please guess a number between 1 and 99>");
uservalue = test.ask();
String correct = ("Congradulations, you guessed the correct answer,");


while(uservalue != genNumber){
if (uservalue > genNumber){
System.out.println("Your guess is too high,");
uservalue = test.ask();
guessCounter ++;
}
else{
System.out.println("Your guess is too low,");
guessCounter ++;
uservalue = test.ask();

}
}
guessCounter ++;
System.out.println(correct);
System.out.println(genNumber + " in " + guessCounter + " guesses");
genNumber = generator.next(99);
guessCounter = 0;
}




}
 
You should use the Random class within the java.util package. The method nextInt() can be used to generate a new random number as shown in the following code :

import java.util.Random;

class RandomNumbers {
public static void main(String [] args) {

int generatedNumber, i;

Random r1 = new Random();
// generate number between 0 and 99

for (i = 0; i < 10; i++) {
generatedNumber = r1.nextInt(100);
System.out.println(generatedNumber);
}
}
}

Each time the class file is executed it will generate ten new random numbers.


 
You should use the Random class within the java.util package. The method nextInt() can be used to generate a new random number as shown in the following code :

import java.util.Random;

class RandomNumbers {
public static void main(String [] args) {

int generatedNumber, i;

Random r1 = new Random();


for (i = 0; i < 10; i++) {
// generate number between 0 and 99
generatedNumber = r1.nextInt(100);
System.out.println(generatedNumber);
}
}
}

Each time the class file is executed it will generate ten new random numbers.


 
This will probubly still produce the same sequence of
randoms. Typically something like a true random is
achieved by using a seed value, usually current time.
Use the Random constructor with a seed value
Random(long seed)
Creates a new random number generator using a single long seed:

This will give a different value everytime.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top