Solved

Checking for $ entries without using try and catch

Posted on 2004-04-03
38
329 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 14
  • 11
  • 5
  • +3
38 Comments
 
LVL 92

Expert Comment

by:objects
ID: 10750029
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
ID: 10750045
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
ID: 10750060
if (Character.isDigit(input.charAt(0)) == false) {
      input = input.substring(1);
}

double money = Double.parseDouble(input);
0
Salesforce Has Never Been Easier

Improve and reinforce salesforce training & adoption using WalkMe's digital adoption platform. Start saving on costly employee training by creating fast intuitive Walk-Thrus for Salesforce. Claim your Free Account Now

 
LVL 92

Expert Comment

by:objects
ID: 10750099
> double money = Double.parseDouble(input);

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

Expert Comment

by:CEHJ
ID: 10750142
>>...requiring a try/catch.


Not so
0
 
LVL 92

Expert Comment

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

Author Comment

by:MikeDnyc
ID: 10750271
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
ID: 10750278
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
ID: 10750280
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
ID: 10750282
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
ID: 10750283
> 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
ID: 10750292
>>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
ID: 10750304
And I suggest you read *all* the q :)
0
 

Author Comment

by:MikeDnyc
ID: 10750312
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
ID: 10750321
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
ID: 10750323
>>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
ID: 10750349
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
ID: 10750363
> 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
ID: 10750379
Not so
0
 

Author Comment

by:MikeDnyc
ID: 10750414
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
ID: 10750416
> 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
ID: 10750419
> 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
ID: 10751461
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
ID: 10751506
>>
CEHJ,
I get Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
>>

Webstorm's response is correct
0
 
LVL 16

Expert Comment

by:gnoon
ID: 10751528
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
ID: 10751538
Sorry

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

should be

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

Expert Comment

by:gnoon
ID: 10751543
Ahh ... Actually it should be

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

Expert Comment

by:Webstorm
ID: 10751545

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
ID: 10752861
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
ID: 10752983
>>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
ID: 10753116
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
ID: 10753253
excellent! CEHJ.
0
 
LVL 92

Expert Comment

by:objects
ID: 10753553
> 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
ID: 10753575
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
ID: 10753615
>> 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
ID: 10753638
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
ID: 10753645
8-)
0
 
LVL 14

Expert Comment

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

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
The viewer will learn how to implement Singleton Design Pattern in Java.
Suggested Courses

737 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