Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    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!

  • #2
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,987
    Thanks
    4
    Thanked 2,660 Times in 2,629 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.

  • #3
    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.

  • #4
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,987
    Thanks
    4
    Thanked 2,660 Times in 2,629 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.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •