• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 338
  • Last Modified:

Checking for $ entries without using try and catch

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
0
MikeDnyc
Asked:
MikeDnyc
  • 14
  • 11
  • 5
  • +3
1 Solution
 
objectsCommented:
without using try/catch you cannot use existing parse methods such as parseInt(), you will need to implement your own parsing method.
0
 
objectsCommented:
To check for $ you can use String methods:

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

or

if (s.charAt(0)=='$')
{
   // first character is $
}
0
 
CEHJCommented:
if (Character.isDigit(input.charAt(0)) == false) {
      input = input.substring(1);
}

double money = Double.parseDouble(input);
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

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

That'll still throw exceptions, requiring a try/catch.
0
 
CEHJCommented:
>>...requiring a try/catch.


Not so
0
 
objectsCommented:
So instead the application will crash, that sounds useful :-D
0
 
MikeDnycAuthor 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, *.*.*
0
 
objectsCommented:
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.
0
 
CEHJCommented:
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);
}
0
 
objectsCommented:
Reason being that they throw an exception if an error is found.

My suggestion would be to use NumberFormat and catch exception when invalid.
0
 
objectsCommented:
> To give an error message you should catch NumberFormatExceptions

Please stick to what was asked in the q.
0
 
CEHJCommented:
>>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
0
 
objectsCommented:
And I suggest you read *all* the q :)
0
 
MikeDnycAuthor 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.
0
 
objectsCommented:
Yes as I said above you'll need to write your own parsing routine.
It is not possible with the Java parsing routines.
0
 
CEHJCommented:
>>I guess it is not possible.

It would be possible, but very long-winded. Why would you want to avoid catching an exception though?
0
 
CEHJCommented:
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...");
            }
0
 
objectsCommented:
> You could do this to match the input you specified earlier:

You're still going to have to catch exceptions.
0
 
CEHJCommented:
Not so
0
 
MikeDnycAuthor 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...");
                  }


            
      }
}
0
 
objectsCommented:
> Not so

ie. instead the app will just crash. Which has already been stated is not what is required.
0
 
objectsCommented:
> 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.

0
 
WebstormCommented:
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;
         }


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

Webstorm's response is correct
0
 
gnoonCommented:
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;
}
0
 
gnoonCommented:
Sorry

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

should be

return ( isDecimal(front) && isDecimal(back) && back.length<=2 );
0
 
gnoonCommented:
Ahh ... Actually it should be

return ( isDecimal(front) && isDecimal(back) && back.length>0 && back.length<=2 );
0
 
WebstormCommented:

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;
}

0
 
MikeDnycAuthor 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;
            }
                        
}


0
 
CEHJCommented:
>>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?
0
 
CEHJCommented:
This keeps prompting until a valid amount is entered:


import java.io.*;

public class Area {
      private static BufferedReader stdin;

      public static void main(String[] args) throws IOException {
            stdin = new BufferedReader(new InputStreamReader(System.in));
            double money = Double.NaN;
            do {
                  money = getInput();
            } while(money == Double.NaN);
            if (money > Double.MIN_VALUE) {
                  System.out.println("You entered $" + money);
            }
      }

      private static double getInput() throws IOException {
            System.out.print("Input a dollar amount (x.xx or x): ");
            String RE_CURRENCY = "\\d+|\\d+\\.\\d{2}";
            String strMoney = stdin.readLine();
            if (strMoney.matches(RE_CURRENCY)) {
                  return Double.parseDouble(strMoney);
            }
            else {
                  System.err.println("Enter valid amount...");
                  return Double.NaN;
            }

      }
}
0
 
kennethxuCommented:
excellent! CEHJ.
0
 
objectsCommented:
> 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.
0
 
MikeDnycAuthor 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 :)

0
 
kennethxuCommented:
>> 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?
0
 
objectsCommented:
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.
0
 
CEHJCommented:
8-)
0
 
kennethxuCommented:
>>  It is still possible to have that code throw an exception.
just mention one of the possibilities
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 14
  • 11
  • 5
  • +3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now