import java.util.Scanner;
    import java.util.Random;
    public class CoinTossing
     {
      static enum Status {HEADS,TAILS};
      static Status Coin;
      static int toss;
      public static void main(String []args)
       {
        Scanner input = new Scanner (System.in);
        Random ranDom = new Random();
        CoinTossing call = new CoinTossing ();
        int heads=0;
        int tails=0;
        int choice;
        int tossTimes=1;
        int loop=1;
        System.out.printf("Toss the Coin.\n1.YES\n2.NO\n");
        choice=input.nextInt();

        while(choice!=2)
         {
           System.out.printf("Toss Times :%d",tossTimes);
           ++tossTimes;
           call.flip(ranDom);
            if(Coin==Status.HEADS)
             {
               ++heads;
             }
            if(Coin==Status.TAILS)
             {
               ++tails;
             }

           System.out.printf("Heads :%d\n",heads);
           System.out.printf("Tails :%d\n",tails);

           System.out.printf("\nToss the Coin.\n1.YES\n2.NO");
           choice=input.nextInt();

           if(choice !=1 && choice!=2)
             {
            for(loop=1;loop<=3;loop++)//give 3 chance for input
             {
                System.out.printf("Wrong Input:%d\n",loop);
                System.out.printf("Please give input btween 1 and 2\n");
                choice=input.nextInt();

                if(choice ==1 | choice ==2)
                {
                    break;
                }
              }
             }

            if(loop==3)
             {
               System.out.printf("Due to wrong Input Program has terminated.\n");
               break;
             }
          }
        System.out.printf("\nTotal Tossed Times:%d\n",tossTimes-1);
        System.out.printf("Total Heads         :%d\n",heads);
        System.out.printf("Total Tails         :%d\n",tails);
       }

       Status flip(Random ranDom)
        {
         toss=ranDom.nextInt(2);
         System.out.printf("\nToss:%d\n",toss);
         if(toss==1)
        {
        Coin=Status.HEADS;
        //return Coin;
        }
       if(toss==0)
        {
        Coin=Status.TAILS;
        //return Coin;
        }
      return Coin;

      }
  }


这是一个抛硬币的代码,它提示用户首先放入不带2的东西进行抛掷。在第一次输入后,用户只能输入1和2。如果输入了其他的1和2,它将使用户再次尝试。它将有3次机会。如果3次输入错误,程序将终止。但问题是它不会在3次错误输入后终止。这将是输入选项。

最佳答案

错误是:

 for(loop=1;loop<=3;loop++)


它应该是

 for(loop=0;loop<3;loop++)


因为,当您退出此循环时,loop等于4,因此以下条件不成立:

 if(loop==3)//you will never enter this if, as loop is 4


或者,您可以将条件更改为

 if(loop == 4)

10-05 22:50
查看更多