Reputation: 884
I am trying to use a random number generator for a small game I am writing. The random generator is in an external class to be called by the main.
I am getting a syntax error as indicated below and cant tell why? Any help would be great!
Code: import java.util.Random;
public class RandomGenerator
{
Random generator = new Random(); // Error here is: Syntax error on token ";", {
for (int i = 0; i < 2; i++) // expected after this token
{
int r = generator.nextInt(2);
}
} // I also get an error here telling me to add an "}"
Upvotes: 0
Views: 2962
Reputation: 16999
You cannot put code inside a class without having a method or block around it. Read this:
Also note that standard Java formatting places opening braces at the end of lines.
Upvotes: 2
Reputation: 310
Shouldn't this part:
Random generator = new Random(); // Error here is: Syntax error on token ";", {
for (int i = 0; i < 2; i++) expected after this token
{
int r = generator.nextInt(2);
}
be in a function? Like:
public static void init()
{
Random generator = new Random();
int r=0;
for (int i = 0; i < 2; i++)
{
r = generator.nextInt(2);
}
}
Upvotes: 1
Reputation: 13890
public class RandomGenerator
{
public static void main (String [] args)
{
Random generator = new Random ();
for (int i = 0; i < 2; i++)
{
int r = generator.nextInt (2);
}
}
}
Upvotes: 2