3 回答
TA贡献1809条经验 获得超8个赞
p1、p2 和 p3 在您的 GuessGame 类中声明,因此您的 GameLauncher 方法看不到这些。您应该将这些变量设为全局变量,或者在 GameLauncher 中声明它们,因为您的 GuessGame 不使用它们。
编辑代码:
class GameLauncher{
public static void main(String[] args){
Player p1 = new Player();
Player p2 = new Player();
Player p3 = new Player();
GuessGame Game1 = new GuessGame();
Game1.startGame(p1);
Game1.startGame(p2);
Game1.startGame(p3);
}
}
public class GuessGame {
void startGame(Player p){
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
p.guess(n);
}
}
class Player{
private int number;
Player(){
number = (int)Math.random();
}
void guess(int n){
if(number == n){
System.out.println("the correct answer");}
System.out.println("the wrong answer");
}
}
TA贡献1850条经验 获得超11个赞
如果你想运行代码:
将您的 main() 方法放在公共类中
利用 。用于访问 GuessGame 属性的运算符。
如果您希望您的代码更好:
更改 GuessGame 中的访问修饰符:public -> private 并使用 getter/setter 进行访问。
对guess() 方法使用if/else 表达式。
公共类 GameLauncher {
public static void main(String[] args) {
GuessGame game1 = new GuessGame();
Player p1 = new Player();
Player p2 = new Player();
Player p3 = new Player();
game1.startGame(p1);
game1.startGame(p2);
game1.startGame(p3);
}
}
class GuessGame {
void startGame(Player p) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
p.guess(n);
}
}
class Player {
private int number;
Player() {
number = (int) Math.random();
}
void guess(int n) {
if (number == n) {
System.out.println("the correct answer");
} else {
System.out.println("the wrong answer");
}
}
}
添加回答
举报