How to use String in switch? - java

IDE throws an NullPointerException when I'm trying to do this. I want to have only 2 genders to choose
public String typeOfGender
{
switch (typeOfGender)
{
case "Male":
typeOfGender = "Male";
break;
case "Female":
typeOfGender = "Female";
break;
default:
System.out.println(" Unrecognized gender." );
}
}

You have not initialized typeOfGender. It is null. That is why. Try
typeOfGender="Male";
By the way your code does not make sense. If typeOfGender equals "Male", you assign "Male" to it??

I use them often with no problems, example below. The only reason yours would throw that is if you are passing null to it.
private string GetMailBody(string regionCode)
{
switch(regionCode)
{
case "qc":
//Do some stuff
break;
default:
//If not specified, we assume US, so we do that.
break;
}
return "String we should have edited above";
}

The NullPointerExeption is caused because your string is null.
However, for future reference, here's an example of as switch-case with a string:
String string = "foo";
switch (string) {
case "foo":
System.out.println("foo");
break;
case "bar":
System.out.println("bar");
break;
default:
System.out.println("Mushroom Stew!");
break;
}

Related

My switch statement is not returning anything?

Im selecting a "Left" from alert dialog and after putting it into convertStatusToCode function should retrun "4" but its not?
final String[] status = {"Left"};
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setTitle("Pick a Status");
builder.setItems(status, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
BookingStatus = convertStatusToCode(status[which]);
HERE IS MY convertStatusToCode FUNCTION but it is not retruning "4" which it should return.
private String convertStatusToCode(String status) {
switch (status) {
case "Processing":
i = "0";
break;
case "Room is Allotted":
i = "1";
break;
case "Sorry All Rooms Are Full":
i = "2";
break;
case "Living":
i = "3";
break;
case "Left":
i = "4";
break;
}
return i;
}
it should look something like this
String getStatusCode(String status) {
switch (status) {
case "Processing":
return "0";
case "Room is Allotted":
return "1";
case "Sorry All Rooms Are Full":
return "2";
case "Living":
return "3";
case "Left":
return "4";
default:
return "default_value";
}
}
Based upon what you've added in the comments, your Switch statement (albeit incomplete) shouldn't be the cause of your problem as the other posters are assuming.
You may have a problem with the completness of your switch cases, but that shouldn't stop the switch to work as intended.
You're saying that you DEBUG this and that i has the value of "" which I cannot understand unless you are not having a return value in scope.
The answer posted by Antonis Radz is how I would write that switch if I had to.
If you write your Convert function to return like so, then you don't need the extra i variable, which we don't know where you declared.
If you debug this line of code (like you said you did)
switch(value) and you're telling us that value == "Left" then the switch is receiving the correct value at runtime.
Now your "Case" is executed (when you set a breakpoint in case "Left". So the switch is, again, performing its function so far.
Then I assume you added another breakpoint in the following line(s):
i = "4";
break;
to see what is going on.
The first breakpoint would hit in the assignment i=... and so the variable i which I assume is declared somewhere in scope as String i (At the very least), is either null or contains an old value. Doesn't matter because the next breakpoint (in the break line) would be reached after i is assigned the value of the String "4". So if you add a watch to i and inspect it right there, it must have the value of "4".
Then you return this i so, again, it should still be "4".
If you did all this, you would have been able to tell much closer where the variable is not being assigned.
Do like this.
public String getstatuscode(String status){
String i="";
switch (status) {
case "Processing":
i = "0";
break;
case "Room is Allotted":
i = "1";
break;
case "Sorry All Rooms Are Full":
i = "2";
break;
case "Living":
i = "3";
break;
case "Left":
i = "4";
break;
default:
i = "-1";
}
return i;
}
Declare i as String or int as your requirement. Method is same.Don't forget to remove quotes if you want to assign i as int.
Another thought to use enum rather than switch-case here which gives more flexibility & reusability.
public enum BookingStatus
{
PROCESSING("Processing", 1),
ALLOTED_ROOM("Room is Allotted", 2),
ALL_FULL("Sorry All Rooms Are Full", 3),
LIVING("Living", 4),
LEFT("LEFT", 5);
private String status;
private int code;
BookingStatus(String status, int code)
{
this.status = status;
this.code = code;
}
public static BookingStatus getCodeFromStatus(String status)
{
for (BookingStatus e : values()) {
if (e.status.equals(status)) {
return e;
}
}
return null;
}
public static void main(String args[]) {
System.out.printf("Code for this status is %s", BookingStatus.getCodeFromStatus("Sorry All Rooms Are Full").code);
}
}
switch (status) {
case "Processing":
i = "0";
break;
case "Room is Allotted":
i = "1";
break;
case "Sorry All Rooms Are Full":
i = "2";
break;
case "Living":
i = "3";
break;
case "Left":
i = "4";
// return "4";
break;
}
return i;
}
use return "4"; you don't print anything in switch cases so switch can't return anything if you want to print in switch cases output then use the print method or return in any programming language.

What does XmlPullParser "eventType" indicate?

I am documenting some code using JD-GUI. Currently working on class that utilizes "XMLPullParser". I have read some documentation, but not really getting a clear picture.
The following is a snippet from a method, I want to know what this "eventType" is indication before and in the switch statement cases. What is the significance of it? The "parser" variable below is of type "XmlPullParser"
while (!poComplete)
{
int eventType = this.parser.next();
if (1 == eventType) {
break;
}
switch (eventType)
{
case 2:
String name = this.parser.getName();
if ("purchaseOrder".equals(name)) {
bufferingData = true;
}
if (bufferingData) {
buf.append("<").append(name).append(">");
}
break;
case 3:
if (bufferingData)
{
String name = this.parser.getName();
buf.append("</").append(name).append(">");
if ("purchaseOrder".equals(name))
{
poComplete = true;
bufferingData = false;
}
}
break;
case 4:
if (bufferingData) {
buf.append(quoteXmlData(this.parser.getText()));
}
break;
}
}
next() method returns eventType of integer.
it is one of the constants defined in XMLPullParser.
see javadoc

Call a function according to a selected Key in Java

I am trying to do a weird thing here in Java.
I have a bean that has the following three functions:
bean.getOne()
bean.getTwo()
bean.getThree()
And I have a key that is a string which could have the following three possible values: "one", "two" and "three"
What I want to do is call bean.getOne() if and only if key has value of "one" and so on.
How do I do the check and call the appropriate function?
Assuming you get String[] values which can contain either one, two or three, you can try something like this:
if(values != null){
List valuesList = Arrays.asList(values);
if(valuesList.contains("one"){
bean.getOne();
}
else if(valuesList.contains("two"){
bean.getTwo();
}
else if(valuesList.contains("three"){
bean.getThree();
}
}
Hope this helps.
switch statements are so 90's.
With Java8 functional approach, you could create a lookup table of names and method references, like this:
import java.util.function.Function;
private Map<String, Function<Bean, String>> methods;
methods = new HashMap<>();
methods.put("one", Bean::getOne);
methods.put("two", Bean::getTwo);
methods.put("three", Bean::getThree);
And then use like this:
public String process(Bean bean, String selector) {
return methods.get(selector).apply(bean);
}
Up to Java7
In the JDK 7 release, you can use a String object in the expression of a switch statement:
You can use a switch instead if-else statements for Strings:
switch (key) {
case "one":
bean.getOne();
break;
case "two":
bean.getTwo();
break;
case "three":
bean.getThree();
break;
}
In this case I think a Switch block or if-else would help:
switch (key.toString()) {
case "one":
bean.getOne();
break;
case "two":
bean.getOne();
break;
case "three":
bean.getOne();
break;
}

Java Switch Case return type

Hi I have a Switch case like
#Override
public <RERURN_TYPE...???> convert(Object argToken, Object argFieldToken) {
Object obj = Precondition.ensureNotNull(argToken, "Input Object");
Field field = (Field) Precondition
.ensureNotNull(argFieldToken, "Field");
Type type = Type.valueOf(field.getType().getName());
switch (type) {
case BYTE:
break;
case SHORT:
break;
case INTEGER:
return Integer.parseInt(argToken.toString());
break;
case LONG:
break;
case FLOAT:
break;
case DOUBLE:
break;
case CHARACTER:
break;
case BOOLEAN:
break;
case STRING:
break;
case BIGINT:
break;
default:
break;
}
return null;
}
Here I am converting the "argToken" value depends on the type of the field. Finally the return value will change according to that field type. So how can I maintain the return type which accepts all the return types.
Can anyone please explain this. I stuck over here...
Please...
Amar
You could design the switch part a lot easier like that:
if(argToken instanceof Integer) {
return (int) argToken;
} else if(/* some other types */) {
//cast and return the other types
} else {
return null;
}
But this would only work with the return type Object. The only alternative would be to write methods for each primitive type.
So there is no real solution.

Different types of variables with the same name into a function

I have this code and I'm wondering if it is possible to do something like that:
switch (typeActivity) {
case 0:
Type1Activity aux=activity1;
break;
case 1:
Type2Activity aux=activity2;
break;
case 2:
Type3Activity aux=activity3;
break;
default:
break;
}
Great thanks to you in advance.
Assuming from the similar names of your types they extend a baseclass called something like TypeActivity, or at least should do it this way ;)
Then you could use:
TypeActivity aux = null;
switch (typeActivity) {
case 0:
aux = activity1;//Type1Activity
break;
case 1:
aux = activity2;//Type2Activity
break;
case 2:
aux = activity3;//Type3Activity
break;
default:
break;
}
Only other way would be using Object as Class Object aux = null; which i wouldn´t recommend since it seems polymorphism / extends are the correct way to go here.
Type1Activity aux = null;
switch (typeActivity) {
case 0:
aux=activity1;
break;
case 1:
aux=activity2;
break;
case 2:
aux=activity3;
break;
default:
break;
}
No you can't, the scope of a variable declared within a switch statement is the whole switch statement. So your code should generate a compile error ("variable aux is already defined", or something like that).
Besides, you never use those variables so the whole code is pointless. If this is a simplification of an actual use case, you should explain in more details what you are trying to achieve.

Categories