Monday 6 June 2016

Chapter 3 Exercise 17, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

*3.17 (Game: scissor, rock, paper) Write a program that plays the popular scissor-rock-paper game. (A scissor can cut a paper, a rock can knock a scissor, and a paper can wrap a rock.) The program randomly generates a number 0 , 1 , or 2 representing scissor, rock, and paper. The program prompts the user to enter a number 0 , 1 , or 2 and displays a message indicating whether the user or the computer wins, loses, or draws. Here are sample runs:
 scissor (0), rock (1), paper (2): 1
    The computer is scissor. You are rock. You won
    scissor (0), rock (1), paper (2): 2
    The computer is paper. You are paper too. It is a draw

public class ProgrammingEx3_17 {
 
 public static void main(String[] args) {
  Scanner input = new Scanner(System.in);
 
  System.out.print("scissor (0), rock (1), paper (2):");
  int guess = input.nextInt();
  int computer = (int) (Math.random() * 3);
  String strComputer = "";
 
  switch (computer) {
  case 0:
   strComputer = "scissor";
   break;
  case 1:
   strComputer = "rock";
   break;
  case 2:
   strComputer = "paper";
   break;
  }
 
  String strGuess = "";
  switch (guess) {
  case 0:
   strGuess = "scissor";
   break;
  case 1:
   strGuess = "rock";
   break;
  case 2:
   strGuess = "paper";
   break;
  default:
   System.out.print("Invalid input.");
   System.exit(0);
  }
 
  System.out.print("The computer is " + strComputer + ". You are "
    + strGuess);
 
  if (computer == guess) {
   System.out.print(" too. It is a draw");
  } else if (computer - guess == 1 || computer - guess == -2) {
   System.out.print(". Computer won.");
  } else if (computer - guess == -1 || computer - guess == 2) {
   System.out.print(". You won.");
  }
 
 }
 
}

No comments :

Post a Comment