We help IT Professionals succeed at work.

Check out our new AWS podcast with Certified Expert, Phil Phillips! Listen to "How to Execute a Seamless AWS Migration" on EE or on your favorite podcast platform. Listen Now

x

Checking for $ entries without using try and catch

MikeDnyc
MikeDnyc asked
on
Medium Priority
354 Views
Last Modified: 2010-08-05
Hi all,

I am fairly new to Java and I am looking for a way to ensure that the users input is valid. Since I am not really familiar wiht try and catch, I do not want to use it.

I tried several things but with no luck. I want to ask the user for how much money s/he has (money = Integer.parseInt(stdin.readLine());) and then make sure s/he can only enter a valid format ( I tried using fmt.format) but it didnt work.

Mike D
Comment
Watch Question

Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
without using try/catch you cannot use existing parse methods such as parseInt(), you will need to implement your own parsing method.
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
To check for $ you can use String methods:

if (-1!=s.indexOf("$"))
{
   // contains a $
}

or

if (s.charAt(0)=='$')
{
   // first character is $
}
CERTIFIED EXPERT
Top Expert 2016

Commented:
if (Character.isDigit(input.charAt(0)) == false) {
      input = input.substring(1);
}

double money = Double.parseDouble(input);
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
> double money = Double.parseDouble(input);

That'll still throw exceptions, requiring a try/catch.
CERTIFIED EXPERT
Top Expert 2016

Commented:
>>...requiring a try/catch.


Not so
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
So instead the application will crash, that sounds useful :-D

Author

Commented:
Objects, I am sorry perhaps my question was not clear enough :(. I dont want to check for  "$" char. I want to make sure they entered a valid dollar amount.

For example:

*.xx (10.22) or just * (10)

and if they enter the following they should get an error message rather than the progremming just crashing:

$*.xx, money, *.xxx , *.xxx, *.*.*
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
I realise that, but without using a try/catch you cannot use any of Java inbuilt parsing and will instead need to implement it yourself.
CERTIFIED EXPERT
Top Expert 2016

Commented:
To give an error message you should catch NumberFormatExceptions

try {
   double money = Double.parseDouble(input);
}
catch (NumberFormatException e) {
   System.err.println("You entered an invalid amount: " + input);
}
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
Reason being that they throw an exception if an error is found.

My suggestion would be to use NumberFormat and catch exception when invalid.
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
> To give an error message you should catch NumberFormatExceptions

Please stick to what was asked in the q.
CERTIFIED EXPERT
Top Expert 2016

Commented:
>>Please stick to what was asked in the q.

I've told you before - don't tell me what to do. And read the question:

>>if they enter the following they should get an error message
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
And I suggest you read *all* the q :)

Author

Commented:
I dont need to use any inbuilt parsing method. I just want to check it without try and catch. I guess it is not possible.
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
Yes as I said above you'll need to write your own parsing routine.
It is not possible with the Java parsing routines.
CERTIFIED EXPERT
Top Expert 2016

Commented:
>>I guess it is not possible.

It would be possible, but very long-winded. Why would you want to avoid catching an exception though?
CERTIFIED EXPERT
Top Expert 2016

Commented:
You could do this to match the input you specified earlier:

            String RE_CURRENCY = "\\d+|\\d+\\.\\d{2}";
            if (args[0].matches(RE_CURRENCY)) {
                  double money = Double.parseDouble(args[0]);
            }
            else {
                  System.err.println("Enter valid amount...");
            }
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
> You could do this to match the input you specified earlier:

You're still going to have to catch exceptions.
CERTIFIED EXPERT
Top Expert 2016

Commented:
Not so

Author

Commented:
CEHJ,
I get Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at Area.main(classArea.java:12) during compile time.

import java.io.*;
class Area
 {
      public static void main(String [] args) throws IOException
      {            
      
      DataInputStream stdin = new DataInputStream(System.in);
                    
       String RE_CURRENCY = "\\d+|\\d+\\.\\d{2}";
                 if (args[0].matches(RE_CURRENCY)) {
                           double money = Double.parseDouble(args[0]);
                  }
                  else {
                           System.err.println("Enter valid amount...");
                  }


            
      }
}
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
> Not so

ie. instead the app will just crash. Which has already been stated is not what is required.
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
> I get Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at Area.main(classArea.java:12) during compile time.

And you will also get exceptions during runtime if invalid data is entered.

Top Expert 2004

Commented:
Hi MikeDnyc,

>> java.lang.ArrayIndexOutOfBoundsException
You must give the input parameter when you run your program.
java ... Area 10.22


    public static void main(String [] args) throws IOException
     {          
         if (args.length<1)
         {
                  System.out.println("First parameter is missing.");
                  return;
         }


CERTIFIED EXPERT
Top Expert 2016

Commented:
>>
CEHJ,
I get Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
>>

Webstorm's response is correct

Commented:
public boolean isValidMoney(String input) {
    if( input.indexOf('.')>-1 ) { // maybe double *.*

        String front = input.substring(0,input.indexOf('.'));
        String back = input.substring(input.indexOf('.')+1,s.length);

        if( back.indexOf('.')>-1 ) return false; // it's *.*.*

        return ( isDecimal(front) && isDecimal(back) );

    } else {  // maybe integer *
        return isDecimal(input);
    }
}

publis boolean isDecimal(String s) {
    for(int i=0;i<s.length;i++)
        if( s.charAt(i)<'0' || s.charAt(i)>'9' )
            return false;
    return true;
}

Commented:
Sorry

return ( isDecimal(front) && isDecimal(back) );

should be

return ( isDecimal(front) && isDecimal(back) && back.length<=2 );

Commented:
Ahh ... Actually it should be

return ( isDecimal(front) && isDecimal(back) && back.length>0 && back.length<=2 );
Top Expert 2004

Commented:

Some corrections :

        return ( isDecimal(front,-1) && isDecimal(back,2) );

    } else {  // maybe integer *
        return isDecimal(input,-1);
    }


public boolean isDecimal(String s,int len) {
    if (((len>0)&&(s.length()!=len))    // fixed length
                 ||(s.length()<1))  // empty string is not decimal
                      return false;
    for(int i=0;i<s.length;i++)
        if( s.charAt(i)<'0' || s.charAt(i)>'9' )
            return false;
    return true;
}

Author

Commented:
Gnoon and webstorm. Thanks so far for this: I get the following error messages at compile time:

C:\j2sdk1.4.2_04\bin>javac classFinances.java
classFinances.java:18: non-static method isValidMoney(java.lang.String) cannot be re
ferenced from a static context
                        isValidMoney(input);
                        ^
classFinances.java:31: cannot resolve symbol
symbol  : variable s
location: class Finances
                                        String back = input.substring(input.inde
xOf('.')+1,s.length);

           ^
classFinances.java:48: cannot resolve symbol
symbol  : variable length
location: class java.lang.String
                        for(int i=0;i<s.length;i++)
                                       ^
Note: classFinances.java uses or overrides a deprecated API.
Note: Recompile with -deprecation for details.
3 errors



From code:



class Finances
{
        public static void main (String []args) throws IOException
      {
                  
                  String input;
                        
                  DataInputStream stdin = new DataInputStream(System.in);
                                                                              
                  input = stdin.readLine();
                  
                  isValidMoney(input);
                  
      }            




            public boolean isValidMoney(String input)
            {
                      if( input.indexOf('.')>-1 )  // maybe double *.*
                        {
                                    
                                     String front = input.substring(0,input.indexOf('.'));
                                     String back = input.substring(input.indexOf('.')+1,s.length);

                                     if( back.indexOf('.')>-1 ) return false; // it's *.*.*

                                     return ( isDecimal(front,-1) && isDecimal(back,2) );

                            } else {  // maybe integer *
                                return isDecimal(input,-1);
                            }
                  }

            public boolean isDecimal(String s,int len)
            {
                        
                      if (((len>0)&&(s.length()!=len))    // fixed length
                                                    ||(s.length()<1))  // empty string is not decimal
                                                     return false;
                           for(int i=0;i<s.length;i++)
                    
                                        if( s.charAt(i)<'0' || s.charAt(i)>'9' )
                                                   return false;
                         return true;
            }
                        
}


CERTIFIED EXPERT
Top Expert 2016

Commented:
>>C:\j2sdk1.4.2_04\bin>javac classFinances.java

Not a good idea to be compiled your own classes inside the java bin directory btw

You seem to have abandoned the simpler answer i gave you earlier - why is that?
CERTIFIED EXPERT
Top Expert 2016
Commented:
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION
excellent! CEHJ.
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
> This keeps prompting until a valid amount is entered:

And will possibly crash due to an uncaught exception.
gnoon provides a better alternative if you really don't want to worry about exceptions.

Author

Commented:
Cehj,

I did not abandon it I just went by Ojects's comment below:

> Not so

ie. instead the app will just crash. Which has already been stated is not what is required.

Well thank you for the answer :)

>> And will possibly crash due to an uncaught exception.
just in case you really don't know although I doubt it.
the condition that might cause an exception has been eliminated by pattern matching. so where can the exception come from?
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010

Commented:
There is no guarantee that all possibilities of exceptions have been eleiminated by pattern matching. It is still possible to have that code throw an exception.
CERTIFIED EXPERT
Top Expert 2016

Commented:
8-)
>>  It is still possible to have that code throw an exception.
just mention one of the possibilities
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.