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);
}
}
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:
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