我在将范围放在脑海中时遇到了一些麻烦。我理解为什么下面的代码不起作用,但我从概念上理解我应该怎么做。
$(window).load(function(){
setTimeout(function(){
$('.popin-window').delay(1000).fadeIn(2000);
});
});
我知道为什么我无法从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();
}
}
拨打display.getGuess()
,因为显示超出了范围。我不明白如何正确地做到这一点。我是否为该方法创建了一个新实例playGame()
,但这并不是正确的。在处理多个对象时,我觉得我错过了面向对象的概念。
答案 0 :(得分:3)
将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;