This question already has an answer here:
- Why can't I do assignment outside a method? 7 answers
I am trying to create a simple program where i have to guess a number. Now in one of the classes i am declaring only a variable in the below format;
class player {
int num; //Declaration
num = (int) (Math.random() * 10);
}
This throws me an error that identifier required and suggests me to create another class with the name number.
But if i do
class player {
int num = (int) (Math.random() * 10); //Declaration + Initialisation
}
It gets accepted without any error. I did look this up and people have asked to get the initialisation done under a method but i could not understand why. Could you please explain me the difference between the above two approach? Java
The problem is actually this line:
num = (int) (Math.random() * 10);
this can not be just done in the Class scope.
You are allowed to split declaration and initialization of a variable only if you are in a method/constructor
otherwise must be done in the same line
Note that you will see/hear about things like
class player {
int num;
{
num = (int) (Math.random() * 10);
}
}
but it is better/ cleaner/ more clear to do that inside the constructor or a method.