Solved

Checking for $ entries without using try and catch

Posted on 2004-04-03
38
296 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
0
Comment
Question by:MikeDnyc
  • 14
  • 11
  • 5
  • +3
38 Comments
 
LVL 92

Expert Comment

by:objects
Comment Utility
without using try/catch you cannot use existing parse methods such as parseInt(), you will need to implement your own parsing method.
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
To check for $ you can use String methods:

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

or

if (s.charAt(0)=='$')
{
   // first character is $
}
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
if (Character.isDigit(input.charAt(0)) == false) {
      input = input.substring(1);
}

double money = Double.parseDouble(input);
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
> double money = Double.parseDouble(input);

That'll still throw exceptions, requiring a try/catch.
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
>>...requiring a try/catch.


Not so
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
So instead the application will crash, that sounds useful :-D
0
 

Author Comment

by:MikeDnyc
Comment Utility
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
 
LVL 92

Expert Comment

by:objects
Comment Utility
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
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
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
 
LVL 92

Expert Comment

by:objects
Comment Utility
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
 
LVL 92

Expert Comment

by:objects
Comment Utility
> To give an error message you should catch NumberFormatExceptions

Please stick to what was asked in the q.
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
>>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
 
LVL 92

Expert Comment

by:objects
Comment Utility
And I suggest you read *all* the q :)
0
 

Author Comment

by:MikeDnyc
Comment Utility
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
 
LVL 92

Expert Comment

by:objects
Comment Utility
Yes as I said above you'll need to write your own parsing routine.
It is not possible with the Java parsing routines.
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
>>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
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
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
 
LVL 92

Expert Comment

by:objects
Comment Utility
> You could do this to match the input you specified earlier:

You're still going to have to catch exceptions.
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
Not so
0
Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

 

Author Comment

by:MikeDnyc
Comment Utility
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
 
LVL 92

Expert Comment

by:objects
Comment Utility
> Not so

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

Expert Comment

by:objects
Comment Utility
> 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
 
LVL 13

Expert Comment

by:Webstorm
Comment Utility
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
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
>>
CEHJ,
I get Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
>>

Webstorm's response is correct
0
 
LVL 16

Expert Comment

by:gnoon
Comment Utility
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
 
LVL 16

Expert Comment

by:gnoon
Comment Utility
Sorry

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

should be

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

Expert Comment

by:gnoon
Comment Utility
Ahh ... Actually it should be

return ( isDecimal(front) && isDecimal(back) && back.length>0 && back.length<=2 );
0
 
LVL 13

Expert Comment

by:Webstorm
Comment Utility

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
 

Author Comment

by:MikeDnyc
Comment Utility
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
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
>>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
 
LVL 86

Accepted Solution

by:
CEHJ earned 125 total points
Comment Utility
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
 
LVL 14

Expert Comment

by:kennethxu
Comment Utility
excellent! CEHJ.
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
> 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
 

Author Comment

by:MikeDnyc
Comment Utility
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
 
LVL 14

Expert Comment

by:kennethxu
Comment Utility
>> 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
 
LVL 92

Expert Comment

by:objects
Comment Utility
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
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
8-)
0
 
LVL 14

Expert Comment

by:kennethxu
Comment Utility
>>  It is still possible to have that code throw an exception.
just mention one of the possibilities
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

For customizing the look of your lightweight component and making it look opaque like it was made of plastic.  This tip assumes your component to be of rectangular shape and completely opaque.   (CODE)
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now