View Single Post
Old 10-05-2012, 05:58 PM   PM User | #2
Fou-Lu
God Emperor


 
Fou-Lu's Avatar
 
Join Date: Sep 2002
Location: Saskatoon, Saskatchewan
Posts: 15,645
Thanks: 4
Thanked 2,449 Times in 2,418 Posts
Fou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to all
This isn't javascript, it's java. Moving to the Java forum.

Given the rules you have specified here, you can tokenize and cast the strings. Pulling from an array of String broken with a space is also sufficient.
This is almost entirely correct. The problem is you cannot pull from String[x] as String is a datatype, not a variable. You need to pull from values[x] instead.
Next to this, a try/catch should be used:
PHP Code:
        try
        {
            
String[] values data.split(" ");
            
num1a values[0];
            
sign values[1];
            
num2a values[2];
            
num1 Double.parseDouble(num1a);
            
num2 Double.parseDouble(num2a);
            
double dResult 0.0;
            if (
sign.equals("+"))
            {
                
dResult num1 num2;
            }
            else if (
sign.equals("-"))
            {
                
dResult num1 num2;
            }
            else if (
sign.equals("*"))
            {
                
dResult num1 num2;
            }
            else if (
sign.equals("/"))
            {
                
dResult num1 num2;
            }
            
JOptionPane.showMessageDialog(null"The result is: " dResult);
        }
        catch (
NumberFormatException ex)
        {
            
JOptionPane.showMessageDialog(null,
                    
"There has been an error in input: " ex.getMessage(),
                    
"Error"JOptionPane.ERROR_MESSAGE);
        }
        catch (
ArrayIndexOutOfBoundsException ex)
        {
            
JOptionPane.showMessageDialog(null,
                    
"There appears to be an error in input format (double op double expected)",
                    
"Error",
                    
JOptionPane.ERROR_MESSAGE);
        } 
Switch can also be used on the sign, but only if it's cast to a char (Java does not allow switches on objects, and String is an object not a primitive).
Fou-Lu is offline   Reply With Quote
Users who have thanked Fou-Lu for this post:
Jposemato (10-09-2012)