Reputation: 43
I’ve learned Java for 1 month. I have a question about my code. There is something wrong.If I press 0, the outcomes only has "Computer win" and "Tie" two situation. So as I press 1 and 2, it only comes out two. What's wrong in here ?
import java.util.Scanner;
public class Hm3 {
public static void main (String[] args) {
int Computer=0,Player=0,tie=0,compic=0,pscore=0;tie=0;
int end = 0;
Scanner scan = new Scanner(System.in);
while (end < 3) {
System.out.print("Enter 0 for Scissors, 1 for Rock, and 2 for Paper : ");
pscore = scan.nextInt();
compic = (int)(Math.random()*2);
switch (pscore){
case 0 :
if (compic == 0){
System.out.println("Tie");
tie++;
}else if (compic == 1){
System.out.println("Computer Win");
Computer++;
}else{
System.out.println("Player Win");
Player++;
end++;
}
break;
case 1 :
if (compic == 0){
System.out.println("Player Win");
Player++;
end++;
}else if (compic == 1){
System.out.println("Tie");
tie++;
}else{
System.out.println("Computer Win");
Computer++;
}break;
case 2 :
if (compic == 0){
System.out.println("Computer Win");
Computer++;
}else if (compic == 1){
System.out.println("Player Win");
Player++;
end++;
}else{
System.out.println("Tie");
tie++;
}break;
default :
System.out.println("The wrong value");
break;
}
}
System.out.println("");
System.out.println("The player wins : " + Player);
System.out.println("The computer wins : " + Computer);
System.out.println("Tie : " + tie);
}
}
Upvotes: 0
Views: 13893
Reputation: 116
Yes I also believe that the problem is with your random number generation. When dealing with integers I prefer to use this method because there is no rounding or casting involved:
Random random = new Random(); //create a random object
random.nextInt(3); //will return a random integer from 0 to 2
The number in the parenthesis of the nextInt() method is the range if you want to go from 1 to 3 just alter it to
random.nextInt(3) + 1;
Upvotes: 3
Reputation: 5619
You've been given the answer, and this isn't code review, but I can't fit this suggestion in a comment. Rather than three very similar sub-switches of a switch (which is what you effectively have, just with if-else), you can decide this with a single switch by offsetting the computer's choice by a number of bits (2 is all you need to encode three choices, but 4 is more convenient when you must use hexadecimal rather than binary literals) and ORing it with the player's choice to produce a number that encodes both moves.
// 0:scissors, 1:rock, 2:paper
private String winner(int player, int computer) {
switch (player | (computer<<4)) {
case 0:
case 0x11:
case 0x22:
return "Tie";
case 0x02: // computer:scissors, player:paper
case 0x10:
case 0x21:
return "Computer wins";
case 0x01:
case 0x12:
case 0x20:
return "Player wins";
default:
return "error";
}
}
Upvotes: 0
Reputation: 18359
You are generating random integers from 0 to 1, not from 0 to 2. To fix, do Math.random()*3
Upvotes: 2