Rock, papers, scissors  JAVA program?

How do I make it so that the program displays a message and exits out when either the user or computer wins 2 rounds?

import java.util.Scanner;

public class Main {

public static void main(String[] args) {

 Scanner input = new Scanner(System.in);

 int cWins, uWins;

 cWins = uWins = 0;

 do {

   int computer = (int)(Math.random() * 3);

   System.out.print("Enter a number: scissor [0], rock [1], paper [2]: ");

  int user = input.nextInt();

  System.out.print("The computer is ");

  switch (computer)

  {

  case 0: System.out.print("scissor."); break;

  case 1: System.out.print("rock."); break;

  case 2: System.out.print("paper."); break;

  }

  System.out.print(" You are ");

  switch (user)

  {

  case 0: System.out.print("scissor"); break;

  case 1: System.out.print("rock"); break;

  case 2: System.out.print("paper"); break;

  default : System.out.println("Pick a number 0, 1, or 2.");

  System.exit(1);

  }

 if (computer == user)

 System.out.println(" too, It is a draw");

 else

 {

  boolean win =

    (user == 2 && computer == 0) ||

  (user == 1 && computer == 0) ||

  (user == 2 && computer == 1);

    if (win)

  {

  System.out.println(". You lose");

  cWins++;

  }

  else

  {

  System.out.println(". You won");

  uWins++;

  }

 }

   System.out.println("Computer wins: " + cWins +

    "\nUser wins: " + uWins);

  } while (Math.abs(cWins - uWins) <= 2);

 }

}

1 Answer

Relevance
  • 2 months ago

    Keep looping so long as both the computer and the user have fewer than 2 wins:

        do {

            [long section that probably should be a separate method to play one game]

        } while (cWins < 2 && uWins < 2);

Still have questions? Get your answers by asking now.