逻辑错误游戏程序

时间:2017-01-25 19:42:52

标签: java loops logic user-input

作为棋盘游戏的一部分,我正在尝试创建的程序是:

1-要求用户输入Enemy基础健康值(promptBaseHp())。

2-程序生成一个乘数(2或3),然后将其乘以基本健康值。

3-敌人基础健康值必须是5,7,9,11,13(数组字段表示这些值),这就是我遇到麻烦的地方,我需要检查用户输入是否允许值(5, 7,9,11,13)。

有些错误我无法弄清楚,当我运行程序时,它会提示用户两次,即使输入了正确的值(5,7,9,11,13)。 有人可以帮助我正确获得该程序的功能(输入一个值,检查值是否为5,7,9,11,13,然后乘以2或3)?

package game1;
 import java.util.Scanner;
  import java.util.Random;

   public class Enemy {
   private String [] armorTyper = {      "Fire","Water","Nature","Steel","Scales","Flesh","Dark"};
private  int [] hpValues = { 5, 7, 9, 11 ,13 };
private int enemyHP = 0 ;

Scanner scanner = new Scanner(System.in);
Random random = new Random();

  public int getFinalHp (){
   return enemyHP;
 }


public int getMultiplier (){
int multiplier = random.nextInt(1) +2 ;
return multiplier;
}


public int promptBaseHp (){

    System.out.println ("Enter base hp value (5 or 7 or 9 or 11 or 13): ");
    int hpValue = scanner.nextInt();
    System.out.println(" enemy base hp entered is :"+ hpValue);
    return hpValue;
   }


public void setBaseHp (){


boolean isAcc = comparing(promptBaseHp());

do{

if(isAcc == true){ enemyHP = getMultiplier() * promptBaseHp() ;
getFinalHp ();
}
else{ System.out.println(" must be 5/7/9/11/13 ! ");
 promptBaseHp();
 isAcc = comparing(promptBaseHp());
}
}while (isAcc == false);
}

public boolean comparing( int val) {
    boolean isAcc = false;
    for (int value : hpValues){
     isAcc = (val == value); 
     if (isAcc == true){ return isAcc; }
     else { System.out.println("invalid entery !");
     isAcc = false;}
    }
    return isAcc;
    }
}





package game1;

public class Exceutor {

 public static void main ( String [] args){

    Enemy enem = new Enemy();

    enem.getMultiplier ();
    System.out.println(" enemy hp multiplier is :"+ enem.getMultiplier());

    enem.setBaseHp ();
    enem.getFinalHp ();

    System.out.println(" enemy final hp is : "+ enem.getFinalHp());



  }

}

1 个答案:

答案 0 :(得分:1)

强烈建议您格式化代码,以便您更有意义阅读。

你明显在多个地方叫它两次:

else{ System.out.println(" must be 5/7/9/11/13 ! ");
 promptBaseHp();
 isAcc = comparing(promptBaseHp());
}

将此更改为

else{ System.out.println(" must be 5/7/9/11/13 ! ");
 int value = promptBaseHp();
 isAcc = comparing(value);
}

你也在这里召唤两次

boolean isAcc = comparing(promptBaseHp());

do{

if(isAcc == true){ enemyHP = getMultiplier() * promptBaseHp() ;

将其更改为:

int valueBaseHp = promptBaseHp();
boolean isAcc = comparing(valueBaseHp);
do{
if(isAcc == true){ enemyHP = getMultiplier() * valueBaseHp ;