while循环只循环一次
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
}
为什么下面代码中的 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
}