Question:
Java applet - Try/Catch logic problem?
raisin_smiles
2009-04-21 11:40:20 UTC
Hate to ask such a simple question, it's been bugging me for ages!

The following code checks if the text field is populated with a number by attempting to convert the text field a string to a double.

It then catches a number exception and displays an error message.

I cannot construct the logic so it ONLY does the calculation if there has been NO errors.

Please see link below, used pastebin as formats the code nicely :-)
http://pastebin.com/m2297498a

Thanks
Rob
Three answers:
BeerMeQuik
2009-04-21 12:02:47 UTC
You can add a boolean flag to your code.



// Button find A has been pressed

boolean errorFound = false;

if (arg0.getSource() == btnFindA)

{

try

{

sideC = Double.parseDouble(txtFindC.getText());

}



catch (NumberFormatException e)

{

// Display Error message as a number has not been entered

errMessage.setText("Please enter a VALID Number for side C");

System.out.println("An error!");

errorFound = true;

}





try

{

sideB = Double.parseDouble(txtFindB.getText());

}



catch (NumberFormatException e)

{

// Display Error message as a number has not been entered

errMessage.setText("Please enter a VALID Number for side B");

System.out.println("An error!");

errorFound = true;

}



//Only calulate if no errors

if (!errorFound){

sideA = Math.sqrt(Math.pow(sideC,2)-Math.pow(sideB,2));

txtFindA.setText(Double.toString(sideA));

}

}
2009-04-21 19:15:23 UTC
Put everything in the try {} block. As soon as something generates an exception, control jumps to either the appropriate catch block, or up the stack to the calling function (and similarly up the chain).



What you want is:



try {

double sideB = Double.parseDouble ( txtFindB.getText() );

double sideC = Double.parseDouble ( txtFindC.getText() );



double sideA = Math.sqrt(Math.pow(sideC,2)-Math.pow(sideB,2));

txtFindA.setText( Double.toString(sideA) );

} catch ( NumberFormatException e ) {

errMessage.setText("Please enter a VALID Number on both sides!");

System.out.println("An error!");

}



The only deficiency is that this will not automatically detect which one failed. You could make a variable to hold this extra information, or just access sideB and sideC to see if they have been specified yet - just set them both to be Double.MIN_VALUE or whatever beforehand; if B has changed but C hasn't, then C's format is incorrect; if B hasn't changed, then B's format is incorrect.
gosub33
2009-04-21 19:21:52 UTC
Simple. Use two flags, booleans. set them to true at initialization time.

boolean cGood = true;

boolean bGood = true;



However, in the catch part, set them to false. You can then do something like:

cGood = false;



Then when you go to do the computation, only execute if both are true:



if (cGood && bGood)

{

[[your code]]

}


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...