我正在尝试在java上完成一个小游戏。 这个游戏基于多种方法。 第一种方法,一个 boolean 值,根据我的游戏是否有足够的生命来给出 true 或 false。
public boolean removeLive(){
this.wastedLives++;
if(this.wastedLives == this.lives) {
restingLives=false;
System.out.println("GAME OVER");
}
if(this.wastedLives < this.lives) {
restingLives=true;
}
return restingLives;
}
因此,如果我实例调用此方法,它会执行应该执行的操作,因为在其他方法(calculateLives)中,我实现了 life=startLives-wastedLives; 的值;
所以现在,我需要设计另一种生成随机数的方法,并且我必须猜测。
public void Play() {
super.rebootGame();
boolean continue=true;
System.out.println("Choose a number between 1 &100: ");
this.myNumber=Integer.parseInt(sc.nextLine());
while(this.myNumber < 1 || this.myNumber > 100) {
System.out.println("Choose again a number between the range");
this.myNumber=Integer.parseInt(sc.nextLine());
}
this.randomN = generateRandomNumber();//Method that generate the random number (int)(Math.random()*100)+1;
setStartingLives(5);
while (continue == true && removeLive() == true) {
if (this.myNumber == this.randomN) {
System.out.println("U WIN!!");
refreshRecord();
continue = false;
} else {
removeLive();
if(continue == true && removeLive() == true) {
if(this.myNumber > this.randomN) {
System.out.println("U have too find a lower number");
} else {
System.out.println("U have too find a higher number");
}
this.myNumber = Integer.parseInt(sc.nextLine());
}
}
}
}
问题是第一个方法, boolean 方法,似乎没有被调用,我不知道为什么。因为我设置了起始生命,并且每次我猜不到随机数时都会请求删除生命。
提前致谢,并对翻译不佳表示歉意。
最佳答案
好吧,由于 CoVid19,我有点笨,所以我们在屏幕前的太多无助于保持清醒的头脑。
首先,第二个 while 下面的第一个 IF 需要另一个条件,因为没有它,它将处于无限循环中。
while (continue==true&&removeLive()==true){
if (this.myNumber==this.randomN){
System.out.println("U WIN!!");
refreshRecord();
continue=false;
} else{
removeLive();
if(continue==true&&removeLive()==true){
if(this.myNumber>this.randomN){
System.out.println("U have too find a lower number");
}
else{
System.out.println("U have too find a higher number");
}
this.myNumber=Integer.parseInt(sc.nextLine());
}
}
并且它必须有另一个 if 或 else 来完成循环。
while (continue==true&&removeLive()==true){
if (this.myNumber==this.randomN){
System.out.println("U WIN!!");
refreshRecord();
continue=false;
} else{
removeLive();
if(continue==true&&removeLive()==true){
if(this.myNumber>this.randomN){
System.out.println("U have too find a lower number");
}
else{
System.out.println("U have too find a higher number");
}
this.myNumber=Integer.parseInt(sc.nextLine());
}
} **if(super.getRestingLives()==false){
continue==false;
}**
我错过的第二件事。 我的 boolean 方法返回一个 boolean 值,但我所做的每次调用也都会休息。所以我需要一个 getter 方法来获取 boolean 值
public boolean getRestingLives(){
return restingLives;
}
第三个也是同样重要的一点是我错误地调用了 super.parameters。 所以我添加了正确的调用
super.setStartingLives(this.startLives);
super.calculateRestingLives(super.getStartingLives());
很抱歉搞乱了话题,但有时有必要提出问题才能得到自己的答案。
关于java - 从另一个方法调用的 boolean 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60786684/