I have to make a rock paper scissors game that includes multiple classes and methods. One of the classes is to establish the Computer player which is supposed to generate a random choice and then see if it won against (didIWin
method) the player's choice. I tested the computer's random choice against the player's choice of rock, paper, and scissors which would tell you if your method is working right. My output is giving me the same answer for all three and I have no clue what I am doing wrong. It has to be in the didIWin
method, I think. Any help would be appreciated.
Here is my code:
public class Computer
{
//instance / member variables
private String choice;
private int choiceNumber;
public Computer()
{
//call random set Choice
randomSetChoice();
}
public String getChoice()
{
return "" + choice;
}
public void randomSetChoice()
{
//use Math.random()
int min = 1;
int max = 4;
choiceNumber = (int)(Math.floor(Math.random() * (max - min) + min));
//use switch case
switch(choiceNumber)
{
case 1: choice = "rock"; break;
case 2: choice = "paper"; break;
case 3: choice = "scissors"; break;
default: choice = "invalid input...try again";
}
}
/*
didIWin(Player p) will return the following values
0 - both players have the same choice
1 - the computer had the higher ranking choice
-1 - the player had the higher ranking choice
*/
public int didIWin(Player p)
{
String pc = p.getChoice();
if(choice == "rock")
{
if(pc == "rock")
{
return 0;
}
else if(pc == "paper")
{
return -1;
}
else
{
return 1;
}
}
else if(choice == "paper")
{
if(pc == "paper")
{
return 0;
}
else if(pc == "scissors")
{
return -1;
}
else
{
return 1;
}
}
else
{
if(pc == "scissors")
{
return 0;
}
else if(pc == "rock")
{
return -1;
}
else
{
return 1;
}
}
}
public String toString()
{
return "" + "Computer chose " + choice + "!";
}
}
Aucun commentaire:
Enregistrer un commentaire