Reputation: 21
I am making this slot machine for my programming class but I do not know how to get the program to ask if they want to play again and thus run again without causing an infinite loop. Any help would be appreciated.
public static void main(String[] args)
{
boolean playAgain = true;
Scanner input = new Scanner(System.in);
System.out.println("Welcome, you have 10 credits! Play (Y/N)");
String choice;
choice = input.nextLine();
int credits = 10;
if ("y".equals(choice))
{
playAgain = true;
} else {
playAgain = false;
}
while (playAgain = true)
{
int sp0 = spin();
int sp1 = spin();
int sp2 = spin();
System.out.println(sp0 +"\t"+ sp1 +"\t"+ sp2);
int answer = evaluate(sp0,sp1,sp2);
int newCred = answer + credits - 1;
System.out.println("Your now have "+ newCred + " credits");
System.out.println("Press y to play again");
String newC = input.nextLine();
}
// TODO code application logic here
}
public static int spin()
{
int num1;
Random rand = new Random();
num1 = rand.nextInt(8);
return num1;
}
public static int evaluate(int e1, int e2, int e3)
{
int num;
if(e1==0 && e2==0 && e3==0)
{
num= 7;
System.out.println("You Win");
}else if (e1==e2 && e2 == e3){
num = 5;
System.out.println("You Win");
}else if ( e1== 0 && e2==0 && e3 != 0 ){
num= 3;
System.out.println("You win");
} else if (e1==e2 && e2==e1 && e3 != e1){
num= 2;
System.out.println("You win");
} else if (e1==0 && e2 !=0 && e3 != 0){
num= 1;
System.out.println("You win");
} else {
num =0;
System.out.println("You Lose");
}
return num;
}
Upvotes: 0
Views: 854
Reputation: 124724
This line probably doesn't do what you expected:
while (playAgain = true)
The =
operator is for assignment, ==
is for comparison.
So this line sets the value of playAgain
to true
,
and the value of the expression is true
as well,
so this is an infinite loop.
What you meant to write was is:
while (playAgain == true)
But you didn't need the ==
operator at all, because you can use boolean expressions directly, like this:
while (playAgain)
But this is not enough.
Inside the body of the while
loop, you have nothing to change the value of playAgain
.
One way to fix that:
while (playAgain) {
int sp0 = spin();
int sp1 = spin();
int sp2 = spin();
System.out.println(sp0 +"\t"+ sp1 +"\t"+ sp2);
int answer = evaluate(sp0,sp1,sp2);
int newCred = answer + credits - 1;
System.out.println("Your now have "+ newCred + " credits");
System.out.println("Press y to play again");
playAgain = "y".equals(input.nextLine());
}
Upvotes: 2
Reputation: 530
playAgain = true
Assign true to playAgain
playAgain == true
Test playAgain equals true
Upvotes: 0