为何含.equals()的if语句会抛出NullPointerException?求解答
Hey there, let's break down this confusing NullPointerException you're running into. I totally get why you're stuck—you initialized your variables, so why is this error popping up? Let's start with the core issue first:
You’re right that calling null.equals(null) will throw a NullPointerException, because you can’t invoke a method on a null reference. The initial variable setup you shared (MenuChoice = "" and MenuOption = "nothing") looks fine, so the problem must be in the code you haven’t included yet—specifically how you handle user input or compare values later on.
First, here’s your provided code formatted clearly for reference:
public static void main(String[] args) { String MenuChoice = ""; String MenuOption = "nothing"; System.out.println("Welcome to my Fashion!"); System.out.println("\n"); System.out.println("Are You Signing In As An <Employee> Or <Admin>?"); // Missing code here: logic to read user input and compare MenuChoice }
Here are the most likely culprits and fixes to try:
You might be accidentally setting
MenuChoicetonulllater
Check all places where you assign a new value toMenuChoiceafter initialization. For example, if your input-reading code has edge cases (like handling empty input or a closed stream) that setMenuChoicetonull, callingMenuChoice.equals(...)will trigger the error.Your equals comparison isn’t null-safe
Even if you thinkMenuChoicecan’t be null, edge cases can slip in. Instead of writing:if (MenuChoice.equals("Employee")) { ... }Use a safer approach by putting the constant value first:
if ("Employee".equals(MenuChoice)) { ... }This way, even if
MenuChoiceends up beingnull, the code won’t throw an error—it’ll just returnfalse.Input reading quirks with
Scanner
If you’re usingScannerto get user input, a common mistake is mixingnextInt()withnextLine(). For example, if you read a number first withnextInt(), it leaves a newline character in the input buffer, so the nextnextLine()might read an empty string (or in rare cases, result innullif the stream is exhausted). Make sure your input handling is consistent.
If you can share the full code (especially the input reading and equals comparison parts), we can pinpoint the exact issue. But for now, start with checking these common pitfalls!
内容的提问来源于stack exchange,提问作者Jay Sorensen

