Globalize an input variable in Java
I am trying to make a lottery game in Java and it uses method calls instead of while loops for looping purposes. However, I cannot get an input variable( such as int bet = input.nextInt()) to be recognized as a variable for other methods. I do not know how to globalize "bet" so it can be used by all the methods instead of just in the method it is a part of. Here is part of my code below, including just the one method called "play()"
public static void play()
{
System.out.println("\nPlay? Yes = 1 No = 2 ");
Scanner input = new Scanner(System.in);
int play = input.nextInt();
if(play == 1)
{
System.out.print("Current balance is " + account);
System.out.print("\nPlace your bet: ");
int bet = input.nextInt();
if((bet <= account) && (bet > 0)){
lottery();
}
else if((bet < 0) || (bet > account)){
play();
}
}
开发者_运维问答else if(play == 2){
System.out.println("Final balance is " + account);
System.exit(0);
}
else{
System.out.println("Invalid input!");
play();
}
}
Simplest answer is to declare play and bet as static class variables.
public class Game {
private static int play = 0;
private static int bet = 0;
public static void play() {
System.out.println("\nPlay? Yes = 1 No = 2 ");
Scanner input = new Scanner(System.in);
play = input.nextInt();
if(play == 1) {
System.out.print("Current balance is " + account);
System.out.print("\nPlace your bet: ");
bet = input.nextInt();
if((bet <= account) && (bet > 0)) {
lottery();
}
else if((bet < 0) || (bet > account)){
play();
}
}
else if(play == 2){
System.out.println("Final balance is " + account);
System.exit(0);
}
else{
System.out.println("Invalid input!");
play();
}
}
Define bet
outside of the play()
method.
If you define bet as a field in the class like :
public class Lottery {
private int bet;
public void lottery() {
...
}
public void play() {
...
}
public static void main(String[] args) {
Lottery lottery = new Lottery();
lottery.play();
}
}
then bet is available in all methods in the class, but not outside.
It is not necessary to make play public, so this can stay nicely inside the scope of the play method. It is considered good practice to give variables no more visibility than strictly needed.
Most people would in this case not make bet a field, but pass it as a parameter to the lottery method. In this case the visibiltiy can even be further restricted to only the play and lottery methods.
A final note is you use of function calls to loop. Since java does not support tail-call-optimisation (and it would not apply here in any case) you are going to fill up the stack and finally die of a stack overflow if you play long enough.
Pass it between methods as a parameter. (Defining it as public is not recommended.) Or, if this is a class, you can make it a member variable (property).
精彩评论