我创建了以下石头,纸,剪刀游戏。我正在尝试创建一种称为“赢家”的方法,该方法告诉用户谁赢得了游戏。我创建了一个变量“ end”,它是方法“ winner”的输出。当我执行$ System.out.println(winner(weapon,computerWeapon))时,它给了我一个编译错误。有人可以帮助调试此问题吗?我是Java的新手。
错误:错误:无法从Game类型静态引用非静态方法Winner(java.lang.String,java.lang.String)
import java.util.Scanner;
public class Game {
String end;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String computerWeapon;
System.out.print("Human, choose your weapon: ");
String weapon = input.next().toLowerCase();
int randomNumber = (int)(Math.random()*(3));
if (randomNumber == 0) {
computerWeapon = "rock";
}
else if (randomNumber == 1) {
computerWeapon = "scissors";
}
else {
computerWeapon = "paper";
}
System.out.println("Computer chooses: " + computerWeapon);
System.out.println(winner( weapon, computerWeapon));
}
public static String winner(String weapon, String computerWeapon){
if (weapon.equals("rock")){
if(computerWeapon.equals("rock")) {
end= "Tie!";
}
else if (computerWeapon.equals("scissors")) {
end = "Human wins!";
}
else if (computerWeapon.equals("paper")) {
end= "Computer wins!";
}
}
else if (weapon.equals("paper")){
if(computerWeapon.equals("rock")) {
end= "Human wins!";
}
else if (computerWeapon.equals("scissors")) {
end= "Computer wins!";
}
else if (computerWeapon.equals("paper")) {
end= "Tie!" ;
}
}
else if (weapon.equals("scissors")){
if(computerWeapon.equals("rock")) {
end= "Computer wins!";
}
else if (computerWeapon.equals("scissors")) {
end= "Tie!";
}
else if (computerWeapon.equals("paper")) {
end= "Human wins!";
}
}
return end;
}
}
答案 0 :(得分:1)
您正在尝试从静态方法numbers = []
def addnumber(a):
global numbers
numbers.append(a)
print(numbers)
button1 = Button(bottomFrame, text="1", command=lambda: addnumber(1))
button2 = Button(bottomFrame, text="2", command=lambda: addnumber(2))
中访问非静态end
变量,这是不正确的。
要对其进行修复,可以将其设置为静态,也可以将其设置为winner()
方法内的局部变量,因为要返回它。
答案 1 :(得分:0)
首先;
在您的代码中,end
参数是非静态的。但是您是从winner(..)
静态方法中调用此参数的。你做不到
在您的静态方法中,您尝试返回字符串。全局变量end
参数将是winner
方法中的内部变量。因此,像这样更改此代码;
public static String winner(String weapon, String computerWeapon) {
String end = "";
if (weapon.equals("rock")) {
if (computerWeapon.equals("rock")) {
end = "Tie!";
} else if (computerWeapon.equals("scissors")) {
end = "Human wins!";
} else if (computerWeapon.equals("paper")) {
end = "Computer wins!";
}
} else if (weapon.equals("paper")) {
if (computerWeapon.equals("rock")) {
end = "Human wins!";
} else if (computerWeapon.equals("scissors")) {
end = "Computer wins!";
} else if (computerWeapon.equals("paper")) {
end = "Tie!";
}
} else if (weapon.equals("scissors")) {
if (computerWeapon.equals("rock")) {
end = "Computer wins!";
} else if (computerWeapon.equals("scissors")) {
end = "Tie!";
} else if (computerWeapon.equals("paper")) {
end = "Human wins!";
}
}
return end;
}