Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Switch case string comparison 1

Status
Not open for further replies.

Scoty

Programmer
Oct 25, 2000
278
US
Hi All!
Sorry if this question is answered elsewhere but am I new to java and haven't quite gotten the javax.swing(yuk [tongue] ) of searching this forum yet. I am looking for code that would enable me to do a work around to do a string object comparison.

The strings that I will be comparing will be of known input Example:
Code:
String myVar = new myVar(userInputFromJComboBox);

Switch (myVar){
      case Office:
             //Do This
      case Store:
             //Do That
      case Storage:
             //Do the other
}

Any Ideas would be greatly appreciated

Thanks
Scoty ::)

"Learn from others' mistakes. You could not live long enough to make them all yourself."
-- Hyman George Rickover (1900-86),
 
//myVar can only be char, int, long, short // basic literal that can shortened to int.
//myVar cannot be String

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class MyCombo3 extends JFrame
{
String listOfItem[] = {"zero","one","two","three","four","five"};
int counter;
JComboBox jc;
public MyCombo3()
{
super("Frame1");
getContentPane().setLayout(new GridLayout(2,2));
jc = new JComboBox(listOfItem);
JButton jb = new JButton("see");
jb.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
int i = jc.getSelectedIndex();
switch (i)
{
case 0: System.out.println("you select 0");
break;
case 1: System.out.println("you select 1");
break;
case 2: System.out.println("you select 2");
break;
case 3: System.out.println("you select 3");
break;
case 4: System.out.println("you select 4");
break;
default: System.out.println("you select 5");
break;
}
}
});
getContentPane().add(jb);
getContentPane().add(jc);
}
public static void main(String args[])
{
MyCombo3 MyComboObj = new MyCombo3();
MyComboObj.setSize(400,400);
MyComboObj.setVisible(true);
}
}
 
//myVar cannot be String
// I can use byte, short, char, int for myVar in switch case
 
basically, you can only use switch statements on primitive data types.

If you need to compare String or Object values you must use a if,else if,else construct.

--------------------------------------------------
Free Database Connection Pooling Software
 
I do like the idea prosper suggested.

You can make an array, Vector or something like that with the options, then use a method like index and the do the case on the int value returned.

That's clearly unefficient and maybe tricky, but that way you can avoid a long list of nested if..else that makes the code difficult to read and maintain.

Cheers.

Dian
 
Thanks everyone for your responses,
I am aware that a string object can not be compared in a switch case. I am a VB programmer who is trying to convert a vb program to java to run on our aix system. There are a lot of select case processes in the vb version. When I took my java course the instructor made mention that there are quite few work arounds for the problem. I have not yet found a viable option for my situation. I was just wondering if anyone had come up with a nifty work around for this (imho) short sighted problem. I will use nested if's if I have too but as Dian mentioned that would make the code difficult to read and a huge monster to maintain. So if you have a link or heard of a guy who had a rooom mate that may have a work around I would greatly appreciate it. As I said I am new to java so if this is just not possible let me know so I can get busy nesting those if's

thanks again
Scoty ::)


"Learn from others' mistakes. You could not live long enough to make them all yourself."
-- Hyman George Rickover (1900-86),
 
Unfortunately there is no workaround, as it makes not sense to have a switch on Objects. You can only use switch on primitive data types, as I mentioned earlier.

It is not an "oversight" as you mention. How would you really compare "equality" with an Object. Via its "string" (not the object String) representation, or via a pointer comparison or what ? I expect you find it "short sighted" because you do not understand the concept of Objects in Java.

VB is a very different kettle of fish to Java ....

Good luck !

--------------------------------------------------
Free Database Connection Pooling Software
 
// try this code
class MySwitch
{
public static void main(String args[])
{
//***
String myInput = "Store";
String myList[] = {"Office","Store","Storage"};
switch (preCompare(myInput,myList))
{
case 0:System.out.println("0 is matched");
break;
case 1:System.out.println("1 is matched");
break;
case 2:System.out.println("2 is matched");
break;
default:System.out.println("no String matched");
break;
}
//*** block of code for each switch case
}
public static int preCompare(String input, String forMatch[])
{
int len = forMatch.length;
for (int i=0; i<len; i++)
if (input.equals(forMatch))
return i;
return -1;
}
}
 
sedj,
Thanks again for your reply. I appologize for earlier comment. You are correct I just am really having a hard time not being able to compare string. As you made mention, Yes this is what I would compare (the toString of the object, not the object itself). However, I do understand the object oriented concept, just not very well (yet). I think I may have found a compromise solution It utilized the Switch and if's (but not nested if's yuk! [tongue]). Let me know what you think
Code:
public static void main(String[] args) {
		/*This could  be utilized to do known string size compairs Bit's 
		and indicator fields (usually only 1 to 2 chars long)*/ 
		
		
		//create the char array which is going to hold the string object's literal string

		char[] argsBreakDown = new  char[2];/* would like to know why I had to 
		make this arrays ubound one more than I am actually using..?*/
		
		argsBreakDown[0] = args[0].charAt(0);
		argsBreakDown[1] = args[0].charAt(1);
		
		switch (argsBreakDown[0])
		{
			//OP
			case 'O':
				if(argsBreakDown[1]=='P'){//notice the == comparison here
				System.out.println("You typed OP");
				break;}
				
			//IP
			case 'I':
				if(argsBreakDown[1]=='P'){
					System.out.println("You typed IP");
					break;}
			//IQ	
				if(argsBreakDown[1]=='Q'){
					System.out.println("You typed IQ");
					break;}
			
			//else	
			default:
				System.out.println("I do not understand " + args[0]);
		}
		
	}
}

Thanks for your input everyone
Scoty ::)

&quot;Learn from others' mistakes. You could not live long enough to make them all yourself.&quot;
-- Hyman George Rickover (1900-86),
 
prosper,
thanks for your replies as well. I like that last code post. I am going to investigate it as well.

thanks
Scoty ::)



&quot;Learn from others' mistakes. You could not live long enough to make them all yourself.&quot;
-- Hyman George Rickover (1900-86),
 
I'm sorry, sedj, but I don't agree with you.

I also think Java is a little "sort sighted" in the switch thingie. Even the Object class has an equals method that could be used inside a switch statement.

For example, if I wanted to do a switch on an object defined by me, I could just override the equals method. Of course, I can do that now by hashing the object or doing any trick to encapsulate it as a primitive type, but it's again too tricky and hard to maintain.

Cheers.

Dian
 
Difference in opinion is what makes the world interesting !!

What defines "equals" is extremely vague - and shouldn't my opinion be plumbed into a switch statement.

The reason why it makes sense to use switch is NOT "niceness of how your code looks" - it is because it is treated differently by the compiler than other "a equals b" comparisons - ie it does not need to allocate large amounts of memory for unknown object sizes - it can allocate a known amount because it only needs a piece of memmory or stack the size of the biggest primitive data type. You cannot introduce objects into it, because you would need to change the way the switch statement works - making it more like the if/elseif/else contstruct. This is why switch only accepts primitive data types, and why it is quicker than if/else constructs/

If you want to do "equals" on objects, then use a Comparator or an if/else construct.

--------------------------------------------------
Free Database Connection Pooling Software
 
Of course, I don't have the perfect solution to this issue. If so, I'd be selling it to Sun ;)

But I still think that Java has a lack here. Because a programming language is not just how powerful and quick it is. It's also very important the quality of the code, if it's clear and easy to mantain. In fact, everything Java does can be done with C, but woulb be a nightmare to read.

So maybe not a switch but a "select", even if it's not much more efficient than a bunch of if/else would make the programs easier to read and to understand.

A typical case would be event handling when multiple events can be caught, or exception handling.

Cheers.

Dian
 
Scoty:

char[] argsBreakDown = new char[2];
/* would like to know why I had to make this arrays
ubound one more than I am actually using..?*/

'2' isn't the ubound (upper bound), but the size of the array.

Diancecht:
You may use switch-statements in a fine readable way, and the java-1.5 will have a new type of enum to make the use more comfortable.
case ZERO:
case GREEN:
...
are fine readable. But of course java wasn't invited to make migration of vb-Programs easy.




seeking a job as java-programmer in Berlin:
 
stefanwagner,

Thanks for the info this makes sense.

and you are correct java wasn't invented to make migration easy but the growing pains will be well worth it when I am able to build full-size, cross-platform applications.

Scoty ::)

&quot;Learn from others' mistakes. You could not live long enough to make them all yourself.&quot;
-- Hyman George Rickover (1900-86),
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top