【问题标题】:While loop only loops onceWhile循环只循环一次
【发布时间】:2015-09-28 12:24:07
【问题描述】:

为什么下面代码中的Coinswhile循环只循环一次?

该程序应该允许玩家拿走他们想要的硬币数量,然后如果他们想要更多的硬币可以返回。出于某种原因,尽管一旦您通过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;
                    }
                }
            }
        }
    }
}

【问题讨论】:

  • 我看不到任何明显的东西。每次取nextInt()时都下一个断点,并确保扫描仪返回的值是你所期望的。
  • 您是否尝试过使用调试器单步执行?
  • 你为什么要使用这个代码两次:user=myScan.nextInt();
  • 我看不到whatGame变成false...主循环将永远运行。
  • 你会从自己确定问题中学到更多,而不是从给出答案中学到更多。

标签: java while-loop


【解决方案1】:

好的,我不懂你的游戏...但是你在循环中设置了Coins=false,那么它就永远不会再运行了。

如果你尝试这样的事情:

    if(user==1)
    {
        Coins=true;          //new line here
        while(Coins) {

while 循环将在每次需要时启动。

您应该重新考虑重新构建您的解决方案。

【讨论】:

    【解决方案2】:
    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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-21
      • 1970-01-01
      • 2015-03-23
      • 2011-11-02
      • 2013-08-12
      • 1970-01-01
      • 1970-01-01
      • 2020-04-29
      相关资源
      最近更新 更多