我不知道为什么这个Java代码不起作用

问题描述

好吧,我在房间程序中进行了转义,而灯光的布尔值不起作用

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,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,light);
    
  }
    
  }
}

好,所以我想知道我对方法或&&运算符是否做错了。我检查以确保useranswer为a,也检查以确保

解决方法

在这里,您为变量分配为false,而不是对其进行比较:

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

您要使用==,而不是=。此外,请考虑到useranswer可能为null,因此您应该执行"A".equals(useranswer)以避免NullPointerException

,

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

代替:

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

像往后一样写您的比较

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

然后,您会收到一个编译器错误,指出您正在使用=而不是==的事实。