I'm doing a BankAccount class and in the constructor I need to validate if the string in which the account number is written, is all numeric. Any ideas on how I can accomplish this? Also, it must be of 4 digits...is there some method of the String class that can give me the length of the string? Thanks in advance.
J.Killa
0
Light Poster
Recommended Answers
Jump to Post
.length()
will give you a string's length..charAt(i)
, where i is an integer will give you the individual character at position i in the string (remember that indices in Java start at 0). So in a loop that goes from 0 to length-1, you can check whether each …
Jump to PostUse length() with strings. The library Apache Commons Lang provides isNumeric() to check strings. I'll give you an example, don't forget to download and add this external jar into your project:
Jump to PostDo you know about exceptions in Java? In your constructor, you can check that the account number is valid and throw an illegal argument exception if it isn't valid. That will prevent the code that called the constructor from continuing.
Another (not as good) option is to construct the …
Jump to PostOK, you can do it like that too. Your BankAccount class is as you describe above. In your tester, you prompt the user for the account info. Then you test to make sure the info is valid. If not, you prompt the user again - you're right, you can do …
Jump to PostI'm not sure Exceptions are your best bet here. They might be, but think carefully about what you want.
Here's an example of a WRONG use of exceptions, which I've actually seen in production code. Never do this:
public boolean isNumeric(String s)
{ try{ Integer.parseInt(s); …
All 21 Replies
kramerd
29
Posting Pro in Training
J.Killa
0
Light Poster
martin5211
37
Posting Whiz in Training
J.Killa
0
Light Poster
kramerd
29
Posting Pro in Training
J.Killa
0
Light Poster
kramerd
29
Posting Pro in Training
jon.kiparsky
326
Posting Virtuoso
jon.kiparsky
326
Posting Virtuoso
J.Killa
0
Light Poster
kramerd
29
Posting Pro in Training
jon.kiparsky
326
Posting Virtuoso
jon.kiparsky
326
Posting Virtuoso
BestJewSinceJC
700
Posting Maven
J.Killa
0
Light Poster
BestJewSinceJC
700
Posting Maven
jon.kiparsky
326
Posting Virtuoso
J.Killa
0
Light Poster
jon.kiparsky
326
Posting Virtuoso
jon.kiparsky
326
Posting Virtuoso
J.Killa
0
Light Poster
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.