Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

problem with calling of a method's object in another method

 
Hamza Fetuga
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please check these codes for me. The variable 'answer' gives zero when called in method run and i need it to retain its value throughout the programme.
The programme generates a number with d method generate() and the method run() checks if the user is right or wrong. If wrong it allows the user to re enter until he gets it. Bt like i said the variable 'answer' is giving me problems




the test package is
 
Ralph Cook
Ranch Hand
Posts: 479
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You have two variables named 'answer' in this code; one is local to the routine generate(), and the other is an instance variable in RandomGame. When you call generate(), your code is setting the local variable in that routine, and then returning it, but nothing is receiving the value that is generated. The instance variable in RandomGame is never given a value, so it is zero.

At some point it appears you wanted to do something like

though you would have to work out where that gets done that ne is the correct object and answer is in the block you want it to be in.

Also: you have run() call itself. That will work, sort of, but is a clumsy way of repeating the actions. I suspect what you want to do is repeat until someone closes the program, or enters a special value on the keyboard, or something. A more common way of doing that is something like

where 'done' gets set to true under some condition and terminates the loop.
 
Aniket S. Kulkarni
Ranch Hand
Posts: 87
Android Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hamza Fetuga Welcome to Ranch.
I agree with Ralph Cook.

You should have variable that will receive the value returned by the function.
Your program should terminate.
Ralph Cook addressed issues correctly.
 
Hamza Fetuga
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much for your suggestions. I will give them a try
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic