我对C和PHP有一些经验,但从未真正触及过OOP。开始使用Headfirst Java书籍并对这个猜谜游戏程序感到困惑。我不太了解该计划的第一部分。在一开始的GuessGame课程中会发生什么?
public class GuessGame{
Player p1;
Player p2;
Player p3;
public void startGame() {
p1=new Player();
p2=new Player();
p3=new Player();
int guessp1=0;
int guessp2=0;
int guessp3=0;
boolean p1isRight=false;
boolean p2isRight=false;
boolean p3isRight=false;
int targetNumber = (int) (Math.Random() * 10);
System.out.println("I'm thinking of a number between 0 and 9...");
while(true) {
System.out.println("Number to guess is " + targetNumber);
p1.guess();
p2.guess();
p3.guess();
guessp1 = p1.number;
System.out.printn("Player one guessed " + guessp1);
guessp2 = p2.number;
System.out.printn("Player two guessed " + guessp2);
guessp3 = p3.number;
System.out.printn("Player three guessed " + guessp3);
if(guessp1==targetNumber)
p1isRight=true;
if(guessp2==targetNumber)
p2isRight=true;
if(guessp3==targetNumber)
p3isRight=true;
if(p1isRight || p2isRight || p3isRight) {
System.out.println("We have a winner!");
System.out.println("Player one got it right? " +p1isRight);
System.out.println("Player two got it right? " +p2isRight);
System.out.println("Player three got it right? " +p3isRight);
System.out.println("Game's up.");
break;
}else
System.out.println("Players will have to try again.");
}
}
}
public class Player {
int number = 0;
public void guess() {
number = (int) (Math.random()*10);
System.out.println("I'm guessing " +number);
}
}
public class GameLauncher {
public static void main (String[] args) {
GuessGame game = new GuessGame();
game.startGame();
}
}
所以这是我不明白的:我得到p1= new Player();
意味着从类播放器创建p1对象但Player p1
是什么意思?它是p1
类型Player
变量的声明吗?
答案 0 :(得分:0)
什么意思是“播放器p1”?
是的,它是p1
类型的实例变量Player
的声明。此外,p1具有类范围,而不是方法范围,因此可以从GuessGame
的任何方法读取/写入(即,如果它在startGame()
内声明,它将仅在该方法中可用) 。
同样,它具有包范围,这意味着与GuessGame
在同一个包中的任何其他类都可以通过GuessGame
的实例读取其值(尽管您发布的代码中没有包声明)。
但是,如果你来自C(而不是C ++),我建议你做一些关于OOP概念的研究,比如封装,继承等,只是为了得到一个粗略的想法。