【发布时间】:2020-12-15 18:45:45
【问题描述】:
我必须制作一个包含多个类和方法的石头剪刀布游戏。
其中一个类是建立计算机播放器,它应该生成一个随机选择,然后查看它是否战胜了(didIWin 方法)玩家的选择。我测试了计算机的随机选择与玩家选择的石头、纸和剪刀,这会告诉你你的方法是否正确。
我的输出对所有三个都给出了相同的答案,我不知道我做错了什么。我认为它必须在didIWin 方法中。任何帮助将不胜感激。
这是我的代码:
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 + "!";
}
}
【问题讨论】:
-
最好用equals()而不是==比较字符串。 == 仅在两个字符串引用同一个对象时才有效。如果字符串以相同的顺序具有相同的字符,则等于有效。
标签: java if-statement output