扫描仪不接受用户输入?

问题描述 投票:0回答:1

我正在根据我在网上看到的教程进行一次小型文本冒险,每次我输入 1,2 或 3 时,它都会一直循环回到我的无效命令。如果用户只输入这 3 个数字中的一个数字以外的任何内容,则支持仅关闭。有任何想法吗?我错过了什么?

      String input = in.nextLine();
      if (input.equals(1)) {
          int damageDealt = rand.nextInt(attackDamage);
          int damageTaken = rand.nextInt(enemyAttackDamage);
          
          enemyHealth -= damageDealt;
          health -= damageTaken;
          
          System.out.println ("\t> You strike the " + enemy + " for " + damageDealt + " damage. ");
          System.out.println ("\t> You receive " + damageTaken + " in retaliation! ");
          
          if(health < 1) {
              System.out.println ("\t> You have taken too much damage, you are too weak to go on!");
              break;
              
          }
          
      }
      else if (input.equals(2)) {
          if(numHealthPots > 0) {
            health += healthPotionHealAmount;
            numHealthPots--;
            System.out.println ("\t You drink a health potion, healing yourself for " + healthPotionHealAmount +"." + "\n\t> You now have " + health + " HP. " + "\n\t> You have " + numHealthPots + " health potions left. \n");  
          }
          else {
              System.out.println("\t You have no health potions left! Defeat an enemy for a chance to get one. ");
          }
      }
      else if (input.equals(3)) {
          System.out.println("\tYou run away from the " + enemy + "!");
          continue GAME;
      }
      else {
          System.out.println("\tInvalid command.");
      }
   }
   
   if(health <1 ) {
       System.out.println("\tYou are too weak to go on.");
       break;
   }

我检查了输入值是否有任何错误,即数字后面是否有任何点。但是什么都没有。

java java.util.scanner text-based
1个回答
0
投票

你正在比较 String 和 int 如果您想遵循相同的方法,请使用它

if(input.equals(Integer.toString(1))){
        // Your code here      
   }
© www.soinside.com 2019 - 2024. All rights reserved.