Reputation:
Why does the Coins
while loop in the code below only loop once?
The program is supposed to allow the player to take the amount of coins that they want and then if they want more coins can go back. For some reason though once you go through the Coins
loop and exit it once, regardless of whether or not you got any coins, it no longer works.
import java.util.Scanner;
public class Coins
{
public static void main(String[]args)
{
int user;
int coins=1000;
int player=0;
boolean Coins=true;
boolean whatGame=true;
while(whatGame)
{
System.out.print("Press 1 to get more coins\n");
Scanner myScan=new Scanner(System.in);
user=myScan.nextInt();
if(user==1)
{
while(Coins)
{
if((coins>100)||(coins==100))
{
System.out.print('\u000C');
coins=coins-100;
player=player+100;
System.out.print("Only "+coins+" coins left.\n\n");
System.out.print("You now have "+player+" coins.\n\n");
System.out.println("Press 1 to get more coins\n\nPress 2 to play another game");
user=myScan.nextInt();
if(user==1)
{
System.out.print('\u000C');
Coins=true;
}
else
{
System.out.print('\u000C');
whatGame=true;
Coins=false;
}
}
else if((user==1)&&(coins<=0))
{
System.out.print('\u000C');
System.out.print("Sorry no coins left.\n");
whatGame=true;
Coins=false;
}
}
}
}
}
}
Upvotes: 1
Views: 459
Reputation: 4712
user=myScan.nextInt(); // from this moment on user may no longer be 1
if(user==1)
{
System.out.print('\u000C');
Coins=true;
}
else // thus this branch is executed
{
System.out.print('\u000C');
whatGame=true;
Coins=false; // setting Coins to false, not re-entering loop
}
Upvotes: 1
Reputation: 5436
Ok, i don't understand your game... but you set Coins=false
inside the loop, then it will never run again.
If you try something like:
if(user==1)
{
Coins=true; //new line here
while(Coins) {
the while loop will start everytime is needed.
You should reconsider reestructuring your solution.
Upvotes: 1