Jump to content
Search In
  • More options...
Find results that contain...
Find results in...
darth_bubbles

Java problem.

switch(arg[arg.length() - 1])

Should be switch(arg.charAt(arg.length()-1))

Recommended Posts

Posted · Original PosterOP

I am making a program and I can across a problem. It compiles but doesn't run the way I want it to.

So I made a simpler copy without the program specific stuff.

Here's the code:

class test{    	static String argIs = "The argument is:";	static String otherArgIs;	public static String Hello(String arg)	{		if (arg.toLowerCase() == "hello")		{			return argIs + " hello";		} else if (arg.toLowerCase() == "hi")		{			switch(arg.length() - 1)			{				case 'i': otherArgIs = argIs.substring(0,argIs.length() - 1);						  return otherArgIs + " hi";				default: return "error1";			}		} else return "error2";	}	public static void main(String[] args)	{		System.out.println( Hello("hello") + Hello("hi") );	}}

I want it to output "The argument is: hello" and "The argument is hi", but it outputs "The argument is: helloerror1"

 

Also, don't pay attention to the uselessness of this program. The actual program is somewhat more useful.

Link to post
Share on other sites

In your switch statement you have 

case 'i':

 which is a letter and not a value to compare against the length. So it goes with the default case.

 

Also

System.out.println( Hello("hello") + Hello("hi") );

is concatenating the string results together without a space or line break.

Link to post
Share on other sites

1) Instead of arg.toLowerCase() == "whatever" do arg.toLowerCase().equals("whatever") otherwise there may be errors since == will compare references and not the actual content. Sometimes it works because it assigns the same object to the same string literals but not necessarily ( http://stackoverflow.com/a/513839

 

2) switch(arg.length() - 1) will search the cases for a number, not a character, you probably want something like switch(arg[arg.length() - 1]) (something like that)

Link to post
Share on other sites

Should be switch(arg.charAt(arg.length()-1))

 

Yeah, ever since I changed my default language from Java to Python I've been spoiled in some ways! (arg[len(arg)-1] is so much better!)

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now


×