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.
kramerd 29 Posting Pro in Training
.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 character is a digit using Character.isDigit(ch)
.
J.Killa 0 Light Poster
Thanks a lot. You've been of great help.
martin5211 37 Posting Whiz in Training
Use 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:
import org.apache.commons.lang.StringUtils;
public class StringTest {
public static void main(String[] args) {
String s = "12345";
System.out.println(s.length());
if(StringUtils.isNumeric(s)) System.out.println("The string is numeric");;
}
}
J.Killa 0 Light Poster
Ok, after reviewing what I did and what I needed to do, I just erased everything and started from scratch...my problem is the following.
I need to do a BankAccount class (I already did it), with methods like deposit, withdraw, etc. That's easy. The difficult part for me is that I have to create an arraylist of bank accounts. The constructor needs an account number, a name, the type of account (savings or check), and the balance.
I need to validate that the account number is a string of length 4 and it must be all digits. I also need to validate that the type of account is available...(s or c). That is my problem, I need to validate those things BEFORE adding the account to the arraylist.
I just need to be pointed in the right direction, I don't expect codes or anything...just need to be guided in the right direction. Like for example, how can I validate this before adding it, and if the validation fails, how do I prevent the account from being added to the arraylist?
kramerd 29 Posting Pro in Training
Do 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 BankAccount object without setting the account number. Then have a different boolean method (setAccountNumber) to set the account number. That method can return false if the account number is invalid.
J.Killa 0 Light Poster
I'm really new programming in Java. Anyways, if for example I make the Bank Account class with a constructor that accepts a Account Number(string), Name(string), Type of Account(char) and Balance(double)...in the Bank Account Tester I can create a Scanner which reads the user input, pass the input as parameters to the constructor and THEN it some type of code I write in the class constructor would let me validate it...I still don't understand where would I put the code that adds the new account if it passes validation. I'm almost certain that it is in the Bank Account Tester...and how would I prevent to add it if it doesn't pass validation and prompt the user to write another account number (I'm almost sure that I have to make do whiles here).
kramerd 29 Posting Pro in Training
OK, 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 this in a do... while loop. If it is valid, then you go ahead and create the BankAccount object and add it to the array list. Does that make sense?
jon.kiparsky 326 Posting Virtuoso
I'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);
return true;
}
catch (NumberFormatException e)
{
return false;
}
}
If you ever come across code like this in a project you're working on, rewrite it. Exceptions are not flow control.
That's not what kramerd was suggesting, but the idea of using exceptions in this context brought it to mind.
I think what kramerd is talking about is making your own Exception - InvalidAccountNumberException, maybe - and throwing that back to the class that's trying to create the account.
That's a valid use of the Exception mechanism, but it seems a bit much for your purposes. In an enterprise sort of application, or a package that will be distributed out of your use, you would use Exceptions in this way to force people to check for things like well-formed account numbers. If you say "throws InvalidAccountNumberException", then anyone using it HAS to catch that and handle it. Try blocks get old real fast.
Maybe you want to play with that - it certainly can't hurt, and it might impress your prof.
However, a simpler way to get the job done would be to
a) validate the String before you use it in the constructor
or
b) write the constructor to take an int, so you have to do the conversion before passing it as a value
or
c) in your constructor, create a boolean to indicate tainted input, and if you come across bad data, set it to true. When you've looked at all of the data, you can decide whether to add the object to the list or not.
Notice that this provides your calling class with the least information about the failure - all you know is that it came back "no", you then have to figure out why. If you use exceptions, you'd be able to return an appropriate exception for each type of failure, and if you validate your data, you'd never call the constructor in the first place. However, this sort of thing is good if you want some insurance against creating a flawed object.
I'd probably go with a validate(String) method that would check that the String represents an acceptable number, and that that number is available (hasn't been assigned already). You might even go ahead and convert that to an int at that point.
If I were actually building something in a work environment, I'd use the exceptions, because I don't want to trust someone later on to get all the checking right - the shortcuts are too tempting.
Edited by jon.kiparsky because: n/a
jon.kiparsky 326 Posting Virtuoso
Hm... I think I mean to say, you want to consider a Factory pattern... :)
J.Killa 0 Light Poster
Ok, here is what I did...I didn't post the code because I speak spanish and I really don't want to translate what I just did...anyway, in the tester I prompted the user to write the account number, the name, the type of account and the balance. I created a validateAccount method (boolean) and validateType(boolean) ...so after I prompted the user to write the parameters, I created a test object of the bankaccount class and passed it's parameters to it, so that I could access the validate methods...if both are true, then I add a new account...now all of this is in a Do...while statement...but now I don't know what to use to get OUT of the do-while. I started to prompt the user to write -1 if he wanted to get out but then it throws an error in the while saying that it can't resolve the variable.
kramerd 29 Posting Pro in Training
Do you want the user to just enter a single account's info, or keep entering account info until they want to quit? If you just want her/him to enter a single account, then you can quit your do...while when the account info is valid. Otherwise, you will have to prompt the user to enter something like "quit" when s/he is done.
By the way, it's ok to post your code "in Spanish". The Java code will still be readable.
jon.kiparsky 326 Posting Virtuoso
So you've wrapped the input in an infinite loop, and you want to break? Define a value that means "break", and check for that. The sentinel value can be anything you like - "0000" or "9999" or "3141" or anything.
Pseudocode for that:
while (!done){
get input;
if input != SENTINEL_VALUE { done = true;}
else {
process as usual
}
}
jon.kiparsky 326 Posting Virtuoso
By the way, it's ok to post your code "in Spanish". The Java code will still be readable.
Y algunos miembros desta comunidad pueden hablar un tanto de español, tambien. Pero debemos continuar en ingles, es mas cortés. :)
BestJewSinceJC 700 Posting Maven
I'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); return true; } catch (NumberFormatException e) { return false; } }
If you ever come across code like this in a project you're working on, rewrite it. Exceptions are not flow control.
That's not what kramerd was suggesting, but the idea of using exceptions in this context brought it to mind.
I think what kramerd is talking about is making your own Exception - InvalidAccountNumberException, maybe - and throwing that back to the class that's trying to create the account.
That's a valid use of the Exception mechanism, but it seems a bit much for your purposes. In an enterprise sort of application, or a package that will be distributed out of your use, you would use Exceptions in this way to force people to check for things like well-formed account numbers. If you say "throws InvalidAccountNumberException", then anyone using it HAS to catch that and handle it. Try blocks get old real fast.
Maybe you want to play with that - it certainly can't hurt, and it might impress your prof.However, a simpler way to get the job done would be to
a) validate the String before you use it in the constructor
or
b) write the constructor to take an int, so you have to do the conversion before passing it as a value
or
c) in your constructor, create a boolean to indicate tainted input, and if you come across bad data, set it to true. When you've looked at all of the data, you can decide whether to add the object to the list or not.Notice that this provides your calling class with the least information about the failure - all you know is that it came back "no", you then have to figure out why. If you use exceptions, you'd be able to return an appropriate exception for each type of failure, and if you validate your data, you'd never call the constructor in the first place. However, this sort of thing is good if you want some insurance against creating a flawed object.
I'd probably go with a validate(String) method that would check that the String represents an acceptable number, and that that number is available (hasn't been assigned already). You might even go ahead and convert that to an int at that point.
If I were actually building something in a work environment, I'd use the exceptions, because I don't want to trust someone later on to get all the checking right - the shortcuts are too tempting.
Disagreed with your "NEVER" statement. Whether or not you return false from within the catch block is highly dependent on the application, the system, and the method. There are probably thousands of examples where returning false from within a catch block is perfectly reasonable code.
J.Killa 0 Light Poster
Jajajaja, now that's nice. Anyway here is my tester at the moment
import java.util.ArrayList;
import java.util.Scanner;
public class BankAccountTester {
public static void main(String[] args) {
ArrayList<BankAccount> cuentas = new ArrayList<BankAccount>();
do
{
Scanner in = new Scanner (System.in);
String num = in.next();
String nam = in.nextLine();
double balan = in.nextDouble();
String t = in.next();
char t2 = t.charAt(0);
BankAccount prueba = new BankAccount(num,nam,t2,balan);
if (prueba.validateNumber(num)&& prueba.validateType(t2));
cuentas.add(new BankAccount(num,nam,t2,balan));
int salir = in.nextInt();
}while(salir != -1);
BestJewSinceJC 700 Posting Maven
Ok, are you having any trouble with it? /What do you still need help with
jon.kiparsky 326 Posting Virtuoso
double balan = in.nextDouble();
It's best to use ints for money: represent the amount in cents or mills (1000ths of a unit) and scale. One advantage is for exact comparison of amounts. Floats are hard to compare precisely.
J.Killa 0 Light Poster
It says that "salir" can't be resolved to a variable.
jon.kiparsky 326 Posting Virtuoso
Scope problem. salir is declared within the do..while block. Declare it at the top of the method and you'll be fine.
jon.kiparsky 326 Posting Virtuoso
Disagreed with your "NEVER" statement. Whether or not you return false from within the catch block is highly dependent on the application, the system, and the method. There are probably thousands of examples where returning false from within a catch block is perfectly reasonable code.
You can get away with it in a simple example like the above, but it's a terrible habit and it sets you up for horrendous bugs. Since code gets more complex over time, not less, using one in a simple case is laying the groundwork for a future maintenance nightmare.
Basically, exceptions are slow, kludgy gotos with two immensely beneficial side effects. They can abort a piece of processing and return useful information, and they can force a user of a method to mind certain pitfalls. If you're using one or both of those side effects, exceptions are great. If you're not, there's always a better way to do it - something that involves not creating extra objects and arbitrary branches.
J.Killa 0 Light Poster
Ok, I took out the salir variable and it's working ...I also noted that it was adding an account to the arraylist whether the if was true or not,but I figured out that the semicolon was wrongly positioned. It's functioning well right now...I'll continue tomorrow because I have to sort it from the lowest acc. number to the biggest as I add the accounts to the array, and be able to show a account based on the account number that the user inputs. I'll figure it tomorrow...thank you guys. You've all been of great help.
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.