vendredi 22 mars 2019

How do I use an if statement to know whether the player or the computer won?

I just started learning java so I may not even be on the right track but I have an assignment that asks me to create a game of 21. The way the game works is that a player and computer take turns entering either a 1, 2, or 3. The player that enters a number that meets or exceeds 21 loses. The trouble I seem to be having is that I cannot seem to get the program to exit the loop when the final number is entered and it will display that the player loses every time, win or lose.

I have tried using another if statement after the do-while loop to display either "You Win!" or "You Lost." However, I can't figure out what parameters I should use in the if statement to decide who won. I also tried to set the game up with the player as even numbers and the computer as odd numbers but I couldn't get the numbers to add to a running total to end the loop.

  int numLoops = 0;
  int firstCheck;
  int points;
  Scanner input = new Scanner(System.in);

  do
  {
     System.out.print("\nEnter a 1, 2, or 3 >> ");
     points = input.nextInt();

     int random = (int )(Math.random() *  3 + 1);
     numLoops = points + numLoops + random;

     if(numLoops < 21)
     {
        System.out.println("The computer entered a " + random);         
        System.out.println("The new total is " + numLoops);
     }
     else
     {
        //This is what always prints.
        System.out.println("You lost! The computer is the victor.");
     }
  }while(numLoops < 21);
  //this is what I am having most of my trouble with.
  System.out.println("You Win!");

I expect that the loop will close after the total reaches 21 and will output a statement That varies based on who won. However, the program always outputs that the player lost.

Aucun commentaire:

Enregistrer un commentaire