public void setupPlayers() {
System.out.println("Would you like the Code Maker to be Human or CPU? :");
String input = mySc.next();
if (input == "Human") {
Player CodeMaker = new Human();
}
else {
Player CodeMaker = new CPU();
}
public void exampleUse() {
CodeMaker.getCode();
}
所以我是 Java 的新手,甚至不确定这是否可以开始。上面的代码都在一个类中。 Human
正在实现接口(interface) Player
。我想在方法 setupPlayers
中使用类 Human
创建一个对象 CodeMaker
,然后在方法 exampleUse< 中使用这个对象
。有没有办法做到这一点?如果没有,谁能想到任何替代方案?干杯。
最佳答案
我认为您一定是说 Player
是界面。请记住,如果您想比较字符串,您应该使用 equals
方法而不是 ==
运算符。
public class ClassName{
private Player codeMaker;
public void setupPlayers() {
System.out.println("Would you like the Code Maker to be Human or CPU? :");
String input = mySc.next();
if (input.equals("Human")) {
codeMaker = new Human();
}
else {
codeMaker = new CPU();
}
}
public void exampleUse() {
codeMaker.getCode();
}
}
关于Java : How to create an object in a method and use it throughout the class?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34420925/