Flash Website Builder- Trendy Site Builder is a Flash Site Building tool that helps users build stunning websites. Check Out Custom Custom Logo Design by LogoBee. Website Design and Free Logo Templates available.
 CodingForums.com Goto and user errors
 User Name Remember Me? Password

Before you post, read our: Rules & Posting Guidelines

 Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
 10-09-2012, 07:29 AM PM User | #1 Jposemato New to the CF scene   Join Date: Oct 2012 Posts: 4 Thanks: 1 Thanked 0 Times in 0 Posts Goto and user errors Okay, start off by saying, i'm new to java. A lot of it confuses. Please bare with me as I make mistakes and won't understand things at first lol. For the following solutions please try to explain why what you did worked though as I am trying to learn with this, not actually make a useful program. Heres the the current program, a basic calculator built to work through JOptionPane panels, I'll explain my problem at the bottom: Code: ```import java.util.*; import javax.swing.*; import java.io.*; import java.util.regex.*; public class Calculator { static Scanner console = new Scanner(System.in); public static void main(String[] args) throws java.lang.NumberFormatException { double num1; double num2; double sum; String sign; String num1a; String num2a; String inStr1; String inStr2; String outStr; int repeats; num1a = "a"; num2a = "b"; sum = 1; inStr1 = JOptionPane.showInputDialog("Please Input an Equation\n" + "* = multiply, / = Divide,\n" + "Include spaces and Decimals (Using Doubles!)\n" + "For example: 2.0 + 4.2, Then ENTER!"); String data = inStr1; String[] values = data.split(" "); num1a = values[0]; sign = values[1]; num2a = values[2]; num1 = Double.parseDouble(num1a); num2 = Double.parseDouble(num2a); if (sign.equals("+")){ sum = num1 + num2; } else if (sign.equals("-")){ sum = num1 - num2; } else if (sign.equals("*")){ sum = num1 * num2; } else if (sign.equals("/")){ sum = num1 / num2; } else { JOptionPane.showMessageDialog(null, "User error. Please follow instructions."); } outStr = (num1 + " " + sign + " " + num2 + " = " + sum); JOptionPane.showMessageDialog(null, ("" + outStr)); JOptionPane.showConfirmDialog(null, "Do More Calculations?", "Calculator", JOptionPane.YES_NO_OPTION); } }``` Okay so right now, that all works fine. The problem is... When you have that guy who really just wants to ruin my work and enter "eb a + asf sakasf" And it throws back a big error. Instead of crashing and returning my java lang exception, how can I make it say something along the lines of "User Error" as I have for the sign (If anything but +, -, /, * entered it returns that.). and then after giving the message go to the Do More Calculations? part. The second question is... and I know i'm going to be hated for this... How do I get around java not having goto? I'm rather used to it and I don't know how to use java to return to the top of the program, perhaps some kind of loop method? I want to make it so if the user presses Yes on "JOptionPane.showConfirmDialog(null, "Do More Calculations?", "Calculator", JOptionPane.YES_NO_OPTION);" it returns to the top. Thanks ahead of time!
 10-09-2012, 03:34 PM PM User | #2 Fou-Lu God Emperor     Join Date: Sep 2002 Location: Saskatoon, Saskatchewan Posts: 16,606 Thanks: 4 Thanked 2,598 Times in 2,567 Posts To prevent errors you must use a try/catch. You need NumberFormatException to prevent a failed cast to double. You can use a generic Exception catch and use instanceof checks to see exactly what it is as well, so you can throw custom exceptions for any and all of the bad checks if desired. Arrays can be counted with a .length property. Use this to your advantage. Finally use a do/while to return control back to the top. Use a sentinal do/while and accept the input from the confirm dialog. Use an integer and compare to the YES_OPTION of the JOptionPane to determine if it should continue. This integer needs to be declared before the do/while in order to use it in the while. Aside from this, regex could be used to determine if the string matches a valid pattern before parsing. Input to performance though, I'd expect that a try/catch would beat a pattern match for this.
 10-16-2012, 07:23 PM PM User | #3 Jposemato New to the CF scene   Join Date: Oct 2012 Posts: 4 Thanks: 1 Thanked 0 Times in 0 Posts Sorry it took me so long to get back, and thanks for helping, however I don't fully understand. This: NumberFormatException I would assume goes by the class start, as my prior experience with exceptions such as "FileNotFoundException" and would start with the throws identifier. This would however send back the error and not resolve the problem. "generic Exception catch and use instanceof checks to see exactly what it is as well, so you can throw custom exceptions for any and all of the bad checks if desired." I've never seen this method before, would it be like an if and be like... Code: ```instanceof (NumberFormatException){ //Insert what happens if user error here }``` Just my guess from looking at it. Again, I suck at this stuff lol. I understand the Do/While part, however I don't understand how to change a variables value by pressing the YES/NO buttons so if you could help with that too thanks ha. Thank you so much for all the help btw.
 10-16-2012, 09:02 PM PM User | #4 Fou-Lu God Emperor     Join Date: Sep 2002 Location: Saskatoon, Saskatchewan Posts: 16,606 Thanks: 4 Thanked 2,598 Times in 2,567 Posts That would be like: PHP Code: ``` try{    ...}catch (Exception ex){    if (ex instanceof NumberFormatException)    {        JOptionPane.showMessageDialog(null, "Failed to parse string as number");    }    if (ex instanceof NumberFormatException)    {        JOptionPane.showMessageDialog(null, "Failed to retrieve tokens - input format invalid");    }}  ``` Catch can be used to catch individual types. I prefer that myself: PHP Code: ``` catch (NumberFormatException ex){    System.err.println("Invalid parse: " + ex.getMessage());}catch (ArrayIndexOutOfBoundsException ex){    System.err.println("Invalid access to array");}catch (Exception ex){    System.err.println("Something went wrong: " + ex.getMessage());}  ``` I'd recommend a final sweep with Exception if it can ever throw an unchecked exception somewhere as well. This way if you miss one it'll still get caught and not terminate the application. JOptionPane.showConfirmDialog will return a result depending on what is clicked. Give it yes/no only options, and compare the results in the while clause: `while (iConfirmContinue == JOptionPane.YES_OPTION);`. Simply assign the confirm dialog to the iConfirmContinue.

 Bookmarks

 Thread Tools Rate This Thread Rate This Thread: 5 : Excellent 4 : Good 3 : Average 2 : Bad 1 : Terrible

 Posting Rules You may not post new threads You may not post replies You may not post attachments You may not edit your posts BB code is On Smilies are On [IMG] code is On HTML code is Off Forum Rules
 Forum Jump User Control Panel Private Messages Subscriptions Who's Online Search Forums Forums Home :: Client side development     JavaScript programming         DOM and JSON scripting         Ajax and Design         JavaScript frameworks         Post a JavaScript     HTML & CSS     XML     Flash & ActionScript         Adobe Flex     Graphics and Multimedia discussions     General web building         Site reviews         Building for mobile devices :: Server side development     Apache configuration     Perl/ CGI     PHP         Post a PHP snippet     MySQL         Other Databases     Ruby & Ruby On Rails     ASP     ASP.NET     Java and JSP     Other server side languages/ issues         ColdFusion         Python :: Computing & Sciences     Computer Programming     Computer/PC discussions     Geek News and Humour Web Projects and Services Marketplace     Web Projects         Small projects (quick fixes and changes)         Medium projects (new script, new features, etc)         Large Projects (new web application, complex features etc)         Unknown sized projects (request quote)         Vacant job positions         Looking for work/ for hire         Project collaboration/ partnership         Paid work offers and requests (Now CLOSED)     Career, job, and business ideas or advice     Domains, Sites, and Designs for sale         Domains for sale         Websites for sale         Design templates and graphics for sale :: Other forums     Member Offers     Forum feedback and announcements

All times are GMT +1. The time now is 01:22 PM.

 AdvertisementLog in to turn off these ads.