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?

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.