【问题标题】:I have no idea why this java code doesn't work [closed]我不知道为什么这个java代码不起作用[关闭]
【发布时间】:2020-08-24 14:53:41
【问题描述】:

好的,所以我做了一个逃离房间的程序,但布尔值不起作用

class Main {
  public static void main(String[] args) {
  System.out.println("Welcome To The Hogwarts Escape Room");
  System.out.println("To Play The Hogwarts Escape Room Press Y");
  Scanner sc = new Scanner(System.in);
  String useranswer = sc.nextLine();
  boolean light = false;
// This is not my entire code but the part that was necessary. 
  System.out.println("Press U to look up");
useranswer = sc.nextLine();
if (usernaswer.equals("U"){
System.out.println(" You look above you and see nothing as the ceiling is too dark to see in.");
    System.out.println("Would you like to: \n Look Closer press A \n Return To Your Original Position press B");
    useranswer = sc.nextLine();
    System.out.println(light);
// this part doesn't work.. I checked and made sure the useranswer was A and the boolean does equal to false.
    if (useranswer.equals("A")&&(light = false)){
      ceilingCloserlightFalse(sc, useranswer, inventory, light);
    }
    else if (useranswer.equals("B")){
      original(sc, useranswer, inventory, light);
    }
// this was the setup to the constructor

public static void ceilingCloserlightFalse(Scanner sc, String useranswer, String [] inventory, boolean light){
    System.out.println("You go closer and see something faintly but cant tell what it is without a light");
    System.out.println("You returned to the original position because there was nothing else to do there.");
    original(sc, useranswer, inventory, light);
    
  }
    
  }
}

好的,所以我想知道我的方法或 && 运算符是否有问题。我检查以确保 useranswer 是 a 并且我还检查以确保

【问题讨论】:

  • light = false 你的意思可能是==。此外,usernaswer 看起来像是一个错字。很难说它为什么不起作用,因为你没有说它应该做什么,也没有说它做什么。

标签: java operators


【解决方案1】:

这里你给变量赋值 false,而不是比较它:

if (useranswer.equals("A")&&(light = false)){
      ceilingCloserlightFalse(sc, useranswer, inventory, light);
    }

您想使用==,而不是=。另外,请考虑 useranswer 可能为 null,因此您应该使用 "A".equals(useranswer) 来避免 NullPointerException

【讨论】:

    【解决方案2】:

    一些开发人员使用 Yoda speak 来避免我们在这里遇到的常见错误。

    代替:

    if (useranswer.equals("A")&&(light = false)){
          ceilingCloserlightFalse(sc, useranswer, inventory, light);
    }
    

    把你的比较写倒像

    if (useranswer.equals("A")&&(false = light)){
          ceilingCloserlightFalse(sc, useranswer, inventory, light);
    }
    

    然后你会得到一个编译器错误,指出你使用的是= 而不是==

    【讨论】:

      猜你喜欢
      • 2021-03-11
      • 1970-01-01
      • 2020-01-11
      • 1970-01-01
      • 2020-09-19
      • 2014-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多