random numbers
hi im trying to return a random number, so far i can generate one and print it out:
import java.util.Random;
/**
* Write a description of class Test here.
*
* @author (your name)
* @version (a version number or a date)
*/
publicclass Test
{
private Random randomGenerator;
public Test()
{
randomGenerator =new Random();
int index = randomGenerator.nextInt(10);
System.out.println(index);
}
}
but if i try to return it i get an error "cannot return a value from method whose result is type void"
publicclass Test
{
private Random randomGenerator;
public Test()
{
randomGenerator =new Random();
int index = randomGenerator.nextInt(10);
return index;
}
thnx chias
Message was edited by:
chias
[1571 byte] By [
chiasa] at [2007-11-27 3:37:58]

thats because your writing all that in a constructor
constructors don't return anything, they also shouldn't really print anything out
a method that returns a random int would be like this
public int randomInt()
{
return randomGenerator.nextInt(10);
}
your Random object should probably be instantiated before the constructor
thnx thats works,
im now have
import java.util.Random;
/**
* Write a description of class Test here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class RandomNumbers
{
private Random randomGenerator;
public RandomNumbers()
{
randomGenerator = new Random();
}
public int getRandomInt()
{
return randomGenerator.nextInt(10);
}
in a class called RandomNumbers
and in another class i have:
public class Game
{
private Parser parser;
private Player player;
private Room currentRoom, previousRoom;
private String playerName;
private int number;
/**
* Create the game and initialise its internal map.
*/
public Game()
{
createRooms();
parser = new Parser();
previousRoom = currentRoom;
player = new Player(10, 0);
number = RandomNumbers.getRandomInt();
here i am trying to set the value of the field number, equal to the random number that was produced but i get an error: "non-static method getRandomInt() cannot be referenced from a static context"
i am not to sure what this means or how to solve the problem, any ideas?