I'm creating a game, and the code that I want Java to run isn't running even when the user inputs a valid answer and I'm not sure how to fix the problem.
I tried creating a keyboard statement for the variable and seperately tried a static String variable name for after the public class, but instead it gives me errors when I originally had none.
This is my original code below:
public static void carMethod (Scanner keyboard)
{
System.out. println ("Now, what is it that you decide to do?");
System.out.println ("Here are your options:");
System.out.println ();
System.out.println ();
System.out.println ("(A.) Go up to the car and see if anyone’s inside.");
System.out.println ("It’s weird enough that a car is in your area anyway");
System.out.println ();
System.out.println ("OR");
System.out.println ();
System.out.println ("(B.) Ignore it. It’s obviously none of your business.");
System.out.println ("So, what’s it going to be?");
System.out.println ("A or B?");
System.out.println ();
String carSelection=keyboard.nextLine();
if (carSelection == "A" || carSelection == "a") {
System.out.println ("You peep into the passenger's side’s windows and don’t notice much");
System.out.println ("other than used soda cans and chip bags scattered across the floor.");
System.out.println ("You also notice that the driver’s sides’s windows are completely open");
System.out.println ("and the keys are casually sitting on top of the driver’s seat, waiting to be taken.");
System.out.println ("What do you plan on doing?");
TextAdventure.searchMethod (keyboard); //note that this is a seperate method and does not have anything to do with the problem
}
if (carSelection == "B" || carSelection == "b") {
System.out.println ("Well my friend…");
System.out.println ("...you let the car be and continue on with your day");
System.out.println ("and nothing eventful ever happens to you again.");
System.out.println ("THE END");
}
}
Any help would be greatly appreciated! Thanks.
When comparing String
s in Java (or any nonprimitive type), you need to use the .equals
method rather than using ==
. You can read more about why here, but the fix is just to say
if (carSelection.equals("A") || carSelection.equals("a")) {
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments