Reputation: 243
I have a String method that I would like to only return the part after the if statement but not the else! I have already tried a try & catch but didn't work either. Is that possible?
PS.This is my first time using stackoverflow.
String split() {
String one = "", two = "";
int index = tableFields.indexOf("(");
if (index > 0){
one = tableFields.substring(0, index);
two = tableFields.substring(index + 1,
tableFields.length() - 1);
}
else {
System.out.println("error");
}
return "`" + one + "`" + " "+ two;
}
Upvotes: 2
Views: 124
Reputation: 527
You can throw an exception in the else, or return null.
Something like
else {
throw new IllegalStateException("Can't split");
}
or
else {
return null;
}
http://www.tutorialspoint.com/java/java_builtin_exceptions.htm provides a list of some built-in exceptions that might be useful, otherwise you could write your own.
Upvotes: 4
Reputation: 863
You can return both in the else and the if.
if (index > 0)
{
one = tableFields.substring(0, index);
two = tableFields.substring(index + 1, tableFields.length() - 1);
return "`" + one + "`" + " "+ two;
}
else
{
System.out.println("error");
return null;
}
Upvotes: 1