简单游戏的java IF语句中的java输出代码错误



我必须制作一个包含多个类和方法的石头剪刀游戏。其中一个类是建立计算机播放器,该播放器应该生成一个随机选择,然后看看它是否战胜了玩家的选择(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 + "!";
}          
}

实际上,如果您测试方法didWin(),它就能工作!

我尝试了这个简单的例子:

public class Main {
static private String str = "scissors";
static private String choice = "paper";
static int didWin(){
String pc = str;
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 static void main(String[] args) {
System.out.println(didWin());
}
}

所有的尝试都奏效了。

请注意,您在问题中写的是didIWin(),而不是didWin(),所以这可能是问题所在。

也许您可以使用Player类和您的一些尝试进行编辑。

最新更新