我在头脑中弄清范围时遇到了一些困难。我明白为什么下面的代码不起作用,但我从概念上不明白我应该如何做。
public class Game {
private String playerName = "";
private int numberOfPegs = 0;
private boolean gameRunning = "True";
public static void main(String[] args) {
Game game = new Game();
game.setupGame();
game.playGame();
}
public void setupGame() {
Display display = new Display();
Code code = new Code();
display.showGreeting();
playerName = display.getUserInput("Enter your name: ");
numberOfPegs = Integer.parseInt(display.getUserInput("How many pegs would you like?"));
code.generateNewCode(numberOfPegs);
}
public void playGame() {
String result = display.getGuess();
}
}
我知道为什么我无法从 playGame()
调用 display.getGuess()
,因为 display 超出了范围。我不明白如何正确执行此操作。我是否为该方法创建一个新实例 Display()
,这感觉不太正确。我觉得在处理多个对象时我缺少面向对象的概念。
最佳答案
将display
设置为实例字段,然后在setupGame()
方法中对其进行初始化。
private String playerName = "";
private int numberOfPegs = 0;
private boolean gameRunning = "True";
private Display display;
public static void main(String[] args) {
Game game = new Game();
game.setupGame();
game.playGame();
}
public void setupGame() {
display = new Display();
Code code = new Code();
display.showGreeting();
playerName = display.getUserInput("Enter your name: ");
numberOfPegs = Integer.parseInt(display.getUserInput("How many pegs would you like?"));
code.generateNewCode(numberOfPegs);
}
public void playGame() {
String result = display.getGuess();
}
声明成员时无需实例化成员。当您声明成员而不实例化时,它将采用其默认值; 0
表示数字类型,false
表示 boolean
,null
表示 Object
类型。所以在这种情况下,
private int numberOfPegs = 0;
与以下内容相同:
private int numberOfPegs;
关于Java 对象范围,从方法引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32120821/