Braces missing return statements? - java

I'm currently writing a program where I have a string of methods all set up basically identical. If they're given i = 1, they'll return the price of the product times the quantity ordered. Otherwise, they simply returned the quantity ordered. Whenever I attempt to compile it, however, the compiler says that the brackets are missing return statements. I've gone through the code several times and I don't see anything overtly wrong in the syntax. Any guesses as to why this is happening?
Thank you for any help.
Relevant Source:
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == switchCard)
{
cl.show(infoPanel, (String)candyList.getSelectedValue());
}
if (e.getSource() == checkoutButton)
{
double acidPops = acidPopsTotal(1);
double bertieBotts = bertieBottsTotal(1);
double bloodPops = bloodPopsTotal(1);
double cauldronCakes = cauldronCakesTotal(1);
double charmChoc = charmChocTotal(1);
double chocoballs = chocoballsTotal(1);
double chocCauldrons = chocCauldronsTotal(1);
double chocFrogs = chocFrogsTotal(1);
double chocWands = chocWandsTotal(1);
double roachClusters = roachClustersTotal(1);
double crystalPineapple = crystalPineappleTotal(1);
double droobleGum = droobleGumTotal(1);
double explodeBonbons = explodeBonbonsTotal(1);
double fizzWhiz = fizzWhizTotal(1);
double iceMice = iceMiceTotal(1);
double jellySlugs = jellySlugsTotal(1);
double liquorWands = liquorWandsTotal(1);
double pepImpts = pepImpsTotal(1);
double pinkIce = pinkIceTotal(1);
double shockChoc = shockChocTotal(1);
double spindleSpiders = spindleSpidersTotal(1);
double quills = quillsTotal(1);
double wizochoc = wizochocTotal(1);
}
}
double acidPopsTotal(int i)
{
if (i == 1)
{
try
{
return (5.95* (Integer.parseInt(acidPopsTF.getText())));
}
catch (NumberFormatException e) {}
}
else
{
try
{
return Integer.parseInt(acidPopsTF.getText());
}
catch (NumberFormatException e) {}
}
}
double bertieBottsTotal(int i)
{
if (i == 1)
{
try
{
return (16.95 * (Integer.parseInt(bertieBottsTF.getText())));
}
catch (NumberFormatException e) {}
}
else
{
try
{
return Integer.parseInt(bertieBottsTF.getText());
}
catch (NumberFormatException e) {}
}
}
double bloodPopsTotal(int i)
{
if (i == 1)
{
try
{
return (5.95 * (Integer.parseInt(bloodPopsTF.getText())));
}
catch (NumberFormatException e) {}
}
else
{
try
{
return Integer.parseInt(bloodPopsTF.getText());
}
catch (NumberFormatException e) {}
}
}
double cauldronCakesTotal(int i)
{
if (i == 1)
{
try
{
return (14.95 * (Integer.parseInt(cauldronCakesTF.getText())));
}
catch (NumberFormatException e) {}
}
else
{
try
{
return Integer.parseInt(cauldronCakesTF.getText());
}
catch (NumberFormatException e) {}
}
}
double charmChocTotal(int i)
{
if (i == 1)
{
try
{
return (5.95 * (Integer.parseInt(charmChocTF.getText())));
}
catch (NumberFormatException e) {}
}
else
{
try
{
return Integer.parseInt(charmChocTF.getText());
}
catch (NumberFormatException e) {}
}
}
double chocoballsTotal(int i)
{
if (i == 1)
{
try
{
return (9.95 * (Integer.parseInt(chocoballsTF.getText())));
}
catch (NumberFormatException e) {}
}
else
{
try
{
return Integer.parseInt(chocoballsTF.getText());
}
catch (NumberFormatException e) {}
}
}
double chocCauldronsTotal(int i)
{
if (i == 1)
{
try
{
return (14.95 * (Integer.parseInt(chocCauldronsTF.getText())));
}
catch (NumberFormatException e) {}
}
else
{
try
{
return Integer.parseInt(chocCauldronsTF.getText());
}
catch (NumberFormatException e) {}
}
}
double chocFrogsTotal(int i)
{
if (i == 1)
{
try
{
return (14.95 * (Integer.parseInt(chocFrogsTF.getText())));
}
catch (NumberFormatException e) {}
}
else
{
try
{
return Integer.parseInt(chocFrogsTF.getText());
}
catch (NumberFormatException e) {}
}
}
double chocWandsTotal(int i)
{
if (i == 1)
{
try
{
return (9.95 * (Integer.parseInt(chocWandsTF.getText())));
}
catch (NumberFormatException e) {}
}
else
{
try
{
return Integer.parseInt(chocWandsTF.getText());
}
catch (NumberFormatException e) {}
}
}
double roachClustersTotal(int i)
{
if (i == 1)
{
try
{
return (5.95 * (Integer.parseInt(roachClustersTF.getText())));
}
catch (NumberFormatException e) {}
}
else
{
try
{
return Integer.parseInt(roachClustersTF.getText());
}
catch (NumberFormatException e) {}
}
}
double crystalPineappleTotal(int i)
{
if (i == 1)
{
try
{
return (9.95 * (Integer.parseInt(crystalPineappleTF.getText())));
}
catch (NumberFormatException e) {}
}
else
{
try
{
return Integer.parseInt(crystalPineappleTF.getText());
}
catch (NumberFormatException e) {}
}
}
double droobleGumTotal(int i)
{
if (i == 1)
{
try
{
return (2.95 * (Integer.parseInt(droobleGumTF.getText())));
}
catch (NumberFormatException e) {}
}
else
{
try
{
return Integer.parseInt(droobleGumTF.getText());
}
catch (NumberFormatException e) {}
}
}
double explodeBonbonsTotal(int i)
{
if (i == 1)
{
try
{
return (9.95 * (Integer.parseInt(explodeBonbonsTF.getText())));
}
catch (NumberFormatException e) {}
}
else
{
try
{
return Integer.parseInt(explodeBonbonsTF.getText());
}
catch (NumberFormatException e) {}
}
}
double fizzWhizTotal(int i)
{
if (i == 1)
{
try
{
return (9.95 * (Integer.parseInt(fizzWhizTF.getText())));
}
catch (NumberFormatException e) {}
}
else
{
try
{
return Integer.parseInt(fizzWhizTF.getText());
}
catch (NumberFormatException e) {}
}
}
double iceMiceTotal(int i)
{
if (i == 1)
{
try
{
return (5.95 * (Integer.parseInt(iceMiceTF.getText())));
}
catch (NumberFormatException e) {}
}
else
{
try
{
return Integer.parseInt(iceMiceTF.getText());
}
catch (NumberFormatException e) {}
}
}
double jellySlugsTotal(int i)
{
if (i == 1)
{
try
{
return (2.95 * (Integer.parseInt(jellySlugsTF.getText())));
}
catch (NumberFormatException e) {}
}
else
{
try
{
return Integer.parseInt(jellySlugsTF.getText());
}
catch (NumberFormatException e) {}
}
}
double liquorWandsTotal(int i)
{
if (i == 1)
{
try
{
return (9.95 * (Integer.parseInt(liquorWandsTF.getText())));
}
catch (NumberFormatException e) {}
}
else
{
try
{
return Integer.parseInt(liquorWandsTF.getText());
}
catch (NumberFormatException e) {}
}
}
double pepImpsTotal(int i)
{
if (i == 1)
{
try
{
return (4.95 * (Integer.parseInt(pepImpsTF.getText())));
}
catch (NumberFormatException e) {}
}
else
{
try
{
return Integer.parseInt(pepImpsTF.getText());
}
catch (NumberFormatException e) {}
}
}
double pinkIceTotal(int i)
{
if (i == 1)
{
try
{
return (4.95 * (Integer.parseInt(pinkCocoIceTF.getText())));
}
catch (NumberFormatException e) {}
}
else
{
try
{
return Integer.parseInt(pinkCocoIceTF.getText());
}
catch (NumberFormatException e) {}
}
}
double shockChocTotal(int i)
{
if (i == 1)
{
try
{
return (4.95 * (Integer.parseInt(shockChocTF.getText())));
}
catch (NumberFormatException e) {}
}
else
{
try
{
return Integer.parseInt(shockChocTF.getText());
}
catch (NumberFormatException e) {}
}
}
double spindleSpidersTotal(int i)
{
if (i == 1)
{
try
{
return (4.95 * (Integer.parseInt(spindleSpidersTF.getText())));
}
catch (NumberFormatException e) {}
}
else
{
try
{
return Integer.parseInt(spindleSpidersTF.getText());
}
catch (NumberFormatException e) {}
}
}
double quillsTotal(int i)
{
if (i == 1)
{
try
{
return (1.95 * (Integer.parseInt(sugarQuillsTF.getText())));
}
catch (NumberFormatException e) {}
}
else
{
try
{
return Integer.parseInt(sugarQuillsTF.getText());
}
catch (NumberFormatException e) {}
}
}
double wizochocTotal(int i)
{
if (i == 1)
{
try
{
return (5.95 * (Integer.parseInt(wizochocTF.getText())));
}
catch (NumberFormatException e) {}
}
else
{
try
{
return Integer.parseInt(wizochocTF.getText());
}
catch (NumberFormatException e) {}
}
}
}
Errors:
C:\Users\Sam\Desktop\Java\4H 2012\ClientApp.java:490: error: missing return statement
}
^
C:\Users\Sam\Desktop\Java\4H 2012\ClientApp.java:510: error: missing return statement
}
^
C:\Users\Sam\Desktop\Java\4H 2012\ClientApp.java:530: error: missing return statement
}
^
C:\Users\Sam\Desktop\Java\4H 2012\ClientApp.java:550: error: missing return statement
}
^
C:\Users\Sam\Desktop\Java\4H 2012\ClientApp.java:570: error: missing return statement
}
^
C:\Users\Sam\Desktop\Java\4H 2012\ClientApp.java:590: error: missing return statement
}
^
C:\Users\Sam\Desktop\Java\4H 2012\ClientApp.java:610: error: missing return statement
}
^
C:\Users\Sam\Desktop\Java\4H 2012\ClientApp.java:630: error: missing return statement
}
^
C:\Users\Sam\Desktop\Java\4H 2012\ClientApp.java:650: error: missing return statement
}
^
C:\Users\Sam\Desktop\Java\4H 2012\ClientApp.java:670: error: missing return statement
}
^
C:\Users\Sam\Desktop\Java\4H 2012\ClientApp.java:690: error: missing return statement
}
^
C:\Users\Sam\Desktop\Java\4H 2012\ClientApp.java:710: error: missing return statement
}
^
C:\Users\Sam\Desktop\Java\4H 2012\ClientApp.java:730: error: missing return statement
}
^
C:\Users\Sam\Desktop\Java\4H 2012\ClientApp.java:750: error: missing return statement
}
^
C:\Users\Sam\Desktop\Java\4H 2012\ClientApp.java:770: error: missing return statement
}
^
C:\Users\Sam\Desktop\Java\4H 2012\ClientApp.java:790: error: missing return statement
}
^
C:\Users\Sam\Desktop\Java\4H 2012\ClientApp.java:810: error: missing return statement
}
^
C:\Users\Sam\Desktop\Java\4H 2012\ClientApp.java:830: error: missing return statement
}
^
C:\Users\Sam\Desktop\Java\4H 2012\ClientApp.java:850: error: missing return statement
}
^
C:\Users\Sam\Desktop\Java\4H 2012\ClientApp.java:870: error: missing return statement
}
^
C:\Users\Sam\Desktop\Java\4H 2012\ClientApp.java:890: error: missing return statement
}
^
C:\Users\Sam\Desktop\Java\4H 2012\ClientApp.java:910: error: missing return statement
}
^
C:\Users\Sam\Desktop\Java\4H 2012\ClientApp.java:930: error: missing return statement
}
^
Note: C:\Users\Sam\Desktop\Java\4H 2012\ClientApp.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
23 errors

There is no return guaranteed due to your try-catch blocks.
You might want to return a sentinel of 0 or -1 to show this.
An example that may make this more clear:
double acidPopsTotal(int i) {
if (i == 1) {
try {
return (5.95* (Integer.parseInt(acidPopsTF.getText())));
} catch (NumberFormatException e) {
//Missing return - compile error
}
} else {
try {
return Integer.parseInt(acidPopsTF.getText());
} catch (NumberFormatException e) {
//Missing return - compile error
}
}
}

In Java it is a compile-time error if there exists at least one path through a non-void function that does not contain a return or a throw. Because you catch a thrown exception and do nothing with it, nothing is returned in that path. Hence, the error.
Aside: you might want to consider a program structure in which you do throw the exception instead of eating it. (Then again, this is probably just example code.)

I believe what TheZ said is correct, there is potential for you to not return anything if an error is caught. Try something like...
double chocFrogsTotal(int i)
{
if (i == 1)
{
try
{
return (14.95 * (Integer.parseInt(chocFrogsTF.getText())));
}
catch (NumberFormatException e) {return -1.;}
}
else
{
try
{
return Integer.parseInt(chocFrogsTF.getText());
}
catch (NumberFormatException e) {return -1.;}
}
}
then whenever you return a value less than 1, you know you had a bad parse.

Related

Do I have to catch a NumberFormatException trying to parse a value to an int or long?

Say I have this method:
public long getLongId(JWTClaimsSet claimsSet)
{
return Long.parseLong(String.valueOf(claimsSet.getClaim(LONG_ID_CLAIM)));
}
public int getIntId(JWTClaimsSet claimsSet)
{
return Integer.parseInt(String.valueOf(claimsSet.getClaim(ID_CLAIM)));
}
for both methods, if I don't send a valid int or long, I want the method to return the defaults, which is 0. Do I need to catch the NumberFormatException here or is this handled internally?
If you are not sure what for data type come from JWTClaimsSet claimsSet than is good if you exclude an potential Exception
public long getLongId(JWTClaimsSet claimsSet) {
try {
return Long.parseLong(String.valueOf(claimsSet.getClaim(LONG_ID_CLAIM)));
} catch (NumberFormatException e) {
return 0;
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
public int getIntId(JWTClaimsSet claimsSet) {
try {
return Integer.parseInt(String.valueOf(claimsSet.getClaim(ID_CLAIM)));
} catch (NumberFormatException e) {
return 0;
} catch (Exception e) {
e.printStackTrace();
return -1;
}

Firebase Exception Not Being Caught

This is my existing code.
mAuth.createUserWithEmailAndPassword(registration.getEmail(), registration.getPassword())
.addOnSuccessListener(this, authResult -> {
Log.i("exception0", "here0");
})
.addOnFailureListener(this, exception -> {
if (exception instanceof FirebaseAuthWeakPasswordException) {
Log.i("exception1", "here");
} else if (exception instanceof FirebaseAuthInvalidCredentialsException) {
Log.i("exception2", "here1");
} else if (exception instanceof FirebaseAuthUserCollisionException) {
Log.i("exception3", "here2");
} else if (exception instanceof FirebaseAuthInvalidUserException) {
Log.i("exception4", "here3");
} else if (exception instanceof FirebaseAuthException) {
Log.i("exception5", "here4");
} else if (exception instanceof FirebaseException) {
FirebaseException firebaseException = (FirebaseException) exception;
Log.i("exception6", "here5" + firebaseException.getMessage());
} else {
Log.i("exception7", "here6");
}
});
I know that the exception needs to be a weak password exception but the exception that does get caught is a FirebaseException.
I even tried the following code
if(!task.isSuccessful()) {
try {
throw task.getException();
} catch(FirebaseAuthWeakPasswordException e) {
mTxtPassword.setError(getString(R.string.error_weak_password));
mTxtPassword.requestFocus();
} catch(FirebaseAuthInvalidCredentialsException e) {
mTxtEmail.setError(getString(R.string.error_invalid_email));
mTxtEmail.requestFocus();
} catch(FirebaseAuthUserCollisionException e) {
mTxtEmail.setError(getString(R.string.error_user_exists));
mTxtEmail.requestFocus();
} catch(Exception e) {
Log.e(TAG, e.getMessage());
}
}
But it would always catch the last generalised exception and not a specific one.
Attempt this:
if(e.getClass().equals(FirebaseAuthWeakPasswordException.class))

Non-Static Generic function that invokes a method passed in as a parameter

I'm trying to consolidate 2 methods into 1, because they handle exceptions the same way. I know in C# you can pass functions/actions as parameters into other functions. I tried creating a generic method to invoke a function, but can't seem to figure it out.
public String getTheStuff(String client) {
try {
return extService.getProduct(client);
} catch (UIException e) {
notHealthy();
} catch (HostException e) {
notHealthy();
} catch (Exception e) {
Throwables.propagate(e);
}
}
public CustomType getsomeMoreStuff(String source, int offset) {
try {
return extService.getMetrics(source, offset);
} catch (UIException e) {
notHealthy();
} catch (HostException e) {
notHealthy();
} catch (Exception e) {
Throwables.propagate(e);
}
}
What I'm looking for is something like
public T invokeExtService(Function functionToInvoke, Parameters[] params){
try {
return functionToInvoke.Invoke(params);
} catch (UIException e) {
notHealthy();
} catch (HostException e) {
notHealthy();
} catch (Exception e) {
Throwables.propagate(e);
}
}
As #LouisWasserman said, this would be much nicer in Java 8, but how about something like this (untested):
public <T> T invoke(Callable<T> function) {
try {
return function.call();
} catch (UIException e) {
notHealthy();
} catch (HostException e) {
notHealthy();
} catch (Exception e) {
Throwables.propagate(e);
}
}
public String getTheStuff(final String client) {
return invoke(new Callable<String>() {
#Override
public String call() {
return extService.getProduct(client);
}
});
}
public CustomType getsomeMoreStuff(final String source, final int offset) {
return invoke(new Callable<CustomType>() {
#Override
public CustomType call() {
return extService.getMetrics(source, offset);
}
});
}
To be honest, I'm not sure how worthwhile this is considering how short your methods are (and they could be even shorter with multi-catch).

How do you get an exception when jsoup times out?

So what I want to do is when my Jsoup connection times out I want to bring up an alert dialog. Right now it does nothing. It just skips over there error and doesn't catch a timeout exception or crash. I'm new to java so I'm not sure how to catch this sockettimeoutexception and reroute it to another method. Can someone tell me how to go to another method when jsoup time out?
private void waterLevel() {
// TODO Auto-generated method stub
try {
levelDoc = Jsoup.connect("http://waterdata.usgs.gov/va/nwis/uv?site_no=02037500roop").timeout(3000).get();
} catch (SocketTimeoutException a) {
Log.e("MyAPP", "Exception----------A!", a);
a.printStackTrace();
alertdialog();
} catch (Exception e) {
Log.e("MyAPP", "Exception----------E!", e);
}
for (Element table : levelDoc.select("table[id=table_07_00065]")) {
String tableText = table.text();
depthArray = tableText.split(" ");
waterLevel = Double.parseDouble(depthArray[4]);
tvWaterLevel.setText(depthArray[4]+"FT");
if(waterLevel >= 5.0 && waterLevel < 9.0){
tvAlert.setText("LIFE JACKET REQUIRED");
}
else if (waterLevel >= 9.0){
tvAlert.setText("HIGH WATER PERMIT REQUIRED");
}
else{
tvAlert.setText("");
}
}
}
So I add changed the code to this and it gives me what i want:
private void waterLevel() {
// TODO Auto-generated method stub
try {
levelDoc = Jsoup.connect("http://waterdata.usgs.gov/va/nwis/uv?site_no=02037500").timeout(4000).get();
} catch (SocketTimeoutException a) {
Log.e("MyAPP", "Exception----------A!", a);
a.printStackTrace();
} catch (Exception e) {
Log.e("MyAPP", "Exception----------E!", e);
}
tvWaterLevel.setText("");
for (Element table : levelDoc.select("table[id=table_07_00065]")) {
String tableText = table.text();
depthArray = tableText.split(" ");
waterLevel = Double.parseDouble(depthArray[4]);
tvWaterLevel.setText(depthArray[4]+"FT");
if(waterLevel >= 5.0 && waterLevel < 9.0){
tvAlert.setText("LIFE JACKET REQUIRED");
}
else if (waterLevel >= 9.0){
tvAlert.setText("HIGH WATER PERMIT REQUIRED");
}
else{
tvAlert.setText("");
}
}
if (tvWaterLevel.length() < 1){
connectionAlarm();
}
}

How to determine the type of primitive in a String representation?

I have a String representation of a primitive and my goal is to determine which primitive is it.
My function is as follows:
public Object getPrimitive(String primitiveAsString) {
.....
}
So for example I would like to return an integer in case the input is "223" but a double if the input is "223.1" or even "223.0"(!!). Moreover, I would like to separate between float and double and even between integer and "BigInteger".
I have tried a solution using NumberFormat and it didn't work for me....
Is there an elegant way to do so?
Thanks!
An idea is just trying to return each type in try-catch.
Code: (the error-checking may be less than ideal)
public static void main(String[] args)
{
System.out.println(getPrimitive("123")); // Byte
System.out.println(getPrimitive("1233")); // Short
System.out.println(getPrimitive("1233587")); // Integer
System.out.println(getPrimitive("123.2")); // Float
System.out.println(getPrimitive("123.999999")); // Double
System.out.println(getPrimitive("12399999999999999999999999")); // BigInteger
System.out.println(getPrimitive("123.999999999999999999999999")); // BigDecimal
}
static public Object getPrimitive(String string)
{
try { return Byte.valueOf(string); } catch (Exception e) { };
try { return Short.valueOf(string); } catch (Exception e) { };
try { return Integer.valueOf(string); } catch (Exception e) { };
try { return new BigInteger(string); } catch (Exception e) { };
try { if (string.matches(".{1,8}"))
return Float.valueOf(string); } catch (Exception e) { };
try { if (string.matches(".{1,17}"))
return Double.valueOf(string); } catch (Exception e) { };
try { return new BigDecimal(string); } catch (Exception e) { };
// more stuff ?
return null;
}
The reasoning behind .{1,8} and .{1,17} is that float and double are accurate to about 7 and 16 digits each (according to some random source). . is a wild-card. {x,y} means repeated between x and y times.
EDIT:
Improved to differentiate float, double and BigDecimal with a basic regex among other things.
I doubt you can do this very easily. It will be very tricky or almost impossible to detect if the contents of the String belongs to integer or BigInteger. You can of course distinguish between int and double/float by writing a regex to determine if it contains '.' and rest of the characters are numbers.
I would do something like this ... this should work for BigInteger and BigDecimal as well ... Haven't tested it though.
public Object getPrimitive(String primitiveAsString) {
String value = primitiveAsString;
try {
return Byte.valueOf(value);
} catch (NumberFormatException ex) { }
try {
return Short.valueOf(value);
} catch (NumberFormatException ex) { }
try {
return Integer.valueOf(value);
} catch (NumberFormatException ex) { }
try {
return Float.valueOf(value);
} catch (NumberFormatException ex) { }
try {
return Double.valueOf(value);
} catch (NumberFormatException ex) { }
try {
return Long.valueOf(value);
} catch (NumberFormatException ex) { }
try {
return new BigInteger(value);
} catch (NumberFormatException ex) { }
try {
return new BigDecimal(value);
} catch (NumberFormatException ex) { }
if(value.length() == 1) {
return new Character(value.charAt(0));
}
return null;
}
EDIT: improved the solution to cater for cases when the input is a BigInteger/BigDecimal. This solution does not use any regex.

Categories

Resources