My code

public class BattleSystem {

    public static void main (String[] args) {
        String choice;
        
        System.out.print("What would you like to do? ");
    	Scanner input = new Scanner(System.in);
    	choice = input.nextLine();
    	System.out.println(choice);
    	
    	if(choice == "1"){
    		createChar g = new createChar();
    		g.charCreateHandler();
    		g.charStatsHandler();
    		g.closeFile();
    	}
    	else{
    		System.out.println("More choices coming soon!");
    	}
    }
}

Console

What would you like to do? 1
1
More choices coming soon!

It should not run my else statement. Help?

Dani AI

Generated

As correctly pointed out, the observed behavior comes from comparing string references instead of their contents; 's char approach works only because it compares primitive values. A few practical, defensive measures make menu-style input more reliable and easier to debug than relying on reference-equality surprises.

Trim and validate the raw input, then either compare the cleaned string or convert it to a numeric option and switch on that. Parsing to an integer and handling bad input keeps the branching clear and avoids subtle whitespace/case issues:

String raw = input.nextLine();
String s = raw.trim();
try {
    int option = Integer.parseInt(s);
    switch (option) {
        case 1:
            // create character
            break;
        default:
            System.out.println("More choices coming soon!");
    }
} catch (NumberFormatException e) {
    System.out.println("Please enter a valid number.");
}

Extra tips: prefer comparing a literal to the variable if you use content-equality to avoid null pointer problems (compare the literal first), consider equalsIgnoreCase for case-insensitive commands, and use next() instead of nextLine() if you want the first token only. If a comparison still fails, print s.length() and each character code to reveal hidden whitespace or control characters. For reference, see the Java String documentation and Scanner behavior: String.equals Javadoc and Scanner.nextLine().

Recommended Answers

All 3 Replies

Strings are not primitive types, so you can't use ==.
you have to use the .equals("String")
Ex. put this in the parenthesis of the if statement

if(choice.equals("1"))

The == operator will only work with primitive types, since a String is an object, you have to use a method to see if it equals another object (i.e. object1.equal(object2))

Not really an answer but if you use

if(choice.charAt(0)=='1')

it works, no idea why the regular comparison won't work though

choice.charAt(0) returns a char, which is a primitive type. The single quotes around 1 means that it is also a primitive type. So the == operator will work.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.