[英]While loop only loops once
為什么下面的代碼中的Coins
while循環僅循環一次?
該程序應該允許玩家取出他們想要的硬幣數量,然后如果他們想要更多的硬幣可以退回。 出於某種原因,盡管一旦您通過Coins
循環並退出一次,無論您是否獲得任何硬幣,它都將不再起作用。
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;
}
}
}
}
}
}
好的,我不了解您的游戲...但是您在循環內設置了Coins=false
,那么它將永遠不會再運行。
如果您嘗試以下操作:
if(user==1)
{
Coins=true; //new line here
while(Coins) {
while循環將在每次需要時啟動。
您應該重新考慮重新構造解決方案。
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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.