problem with using a method's object/variable in another method. Please help!!!
Pls 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
import java.util.Random;
import java.util.Scanner;
public class RandomGame{
public static Random nw= new Random();
static String outcome;
static int answer;
static int gap;
static int guess;
static int realAns;
public static void run()
{
System.out.println(answer);
System.out.println("ENTER ANY NUMBER FROM 1 TO 10");
Scanner input = new Scanner(System.in);
int guess= input.nextInt();
System.out.println(guess);
int gap= answer-guess;
if ((gap<=-3)||(gap>=3) )
{
outcome="Too far. Try again";
}
else
{
outcome="Very close. Try again";
}
if (guess==answer)
{
System.out.println("CONGRATULATIONS. YOU GUESSED THE NUMBER!");
}
else
{
System.out.println(outcome);
run();
}
}
public static int generate()
{
int answer= 1+ nw.nextInt(10);
System.out.println(answer);
return answer;
}
}
the test package is
public class test run{
public static void main(String args())
{
RandomGame ne= new RandomGame();
ne.generate(),
ne.run();
}
Re: problem with using a method's object/variable in another method. Please help!!!
Quote:
The programme generates a number with d method generate()
If we look at the method in question:
Code:
public static int generate()
{
int answer= 1+ nw.nextInt(10);
System.out.println(answer);
return answer;
}
we see that it returns a randomly generated method to the caller, the main() method of another class and that's all. In particular it does not set the value of answer within the RandomGame class. There are two variables here: the static int of the RandomGame class and the local variable within the generate() method. The one in the method is said to shadow the one in the class.
-----
You should use standard Java coding conventions: classes begin with a capital letter and variables should be descriptive of what the variables are.
Consider removing all static variables and methods. Nothing need be static except the main() method of the driver program.