Hi, I am new to java.Please help me in solving this problem. I have written a small program proably took the help from the book Head first java.
Its giving me compilation error when i am trying to access variable GNum ie at lines Player1Num =Player1.GNum;,Player2Num =Player2.GNum; and Player3Num =Player3.GNum;. Error coming is "Cannot find sysmbol variable GNum".How do I access the variable of a method defined in a class from another class.
This is the same way this code is written in head first java.
If any one has the answer please reply. class GuessGame { Player Player1 = new Player(); Player Player2 = new Player(); Player Player3 = new Player();
int Player1Num=0; int Player2Num=0; int Player3Num=0;
if (P1IsRight || P2IsRight || P3IsRight) { System.out.println("We have winner"); System.out.println("Is Player1 a winner?" + P1IsRight); System.out.println("Is Player2 a winner?" + P2IsRight); System.out.println("Is Player3 a winner?" + P3IsRight); break; } else { System.out.println("Lets play the game again as we dont have any winner"); } } } }
class Player {
int GuessNum;
public void Guess() { int GNum = (int) (Math.random() * 10); System.out.println("I am guessing the number as" +GNum); } }
GuessGame Game = new GuessGame(); Game.StartGame(); } }
Vishal Matere
Ranch Hand
Joined: Jan 22, 2008
Posts: 81
posted
0
GNum is locale variable inside method. Please make it instance variable inside the class and mark it as public.
V
SCJP <br />SCWCD <br />SCBCD <br />SCEA-1
rakhee gupta
Ranch Hand
Joined: May 01, 2008
Posts: 43
posted
0
Thank you.It worked
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32712
4
posted
0
Originally posted by Vishal Matere: GNum is locale variable inside method. Please make it instance variable inside the class and mark it as public.
V
Public?
Avoid making fields public. You are right to make gNum (please spell it like that) a field, but give it private access and set up a getGNum() method to allow access to it.
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32712
4
posted
0
Like thisand in the Player class. . . and avoid while(true) . . . break; Change it to while(!(P1isRight || P2isRight || P3isRight)) . . . and lose the break;