I am receiving an account number which is integers. If it is not entered as an integer I wish to state not valid and re-enter account number. If it is all ok I wish to convert all the integer values to a String.
Is it possible to say if accountNumber not equal to an integer?
However, I get the following error when compiling:
C:\java\BankAccount>javac Current.java Current.java:28: cannot resolve symbol symbol : method parseInt (int) location: class java.lang.Integer newAccNo = Integer.parseInt(newAccNo);
I also noted your comment with:
however, I kept this in and didn't use the message to enter an integer:
as my input is coming into the constructor from the TestClass i.e.
In the test class the current account number in the example is primitive however I wanted to validate whether it was all numbers/integers and if not then say invalid account number. This is for future use.
in which case you really do not need to validate the account number. The constructor accepts a String and an int. Any attempt to pass anything else other than an int would cause a compilation error.
Some other points.
1. Consider moving the kind of work that's in your constructor to a private method and call that method from your constructor.
2. Again what is it that you seek to achieve by the while loop. You would ideally have a loop such as the one you have written when you have multiple values to check. Inside the constructor, there is only one account number.
3. your catch statement jusr prints out a warning - this is dangerous practise.
All the above's general advice. As mentioned earlier, in this particular case, you need not check for integer in the constructor as java would throw an exception if you attempt to pass anything else.
Suppose I have a String coming in i.e "1234L" And I wish to check whether or not the String only contains numbers... i.e. excludes everything else other than integers
Just do Integer.parseInt(input); This wopuld throw a NumberFormatException, catch this exception, inform the user about the error and exit.
Also you mention about not using warning messages? Could you elaborate here i.e. why not? And what is the alternative?
OK, this is about the way you code your catch blocks. All you do in your catch blocks is print out an error msg. The program would do exactly that and continue with executing the rest of the code where it may potentially fail.
take a look at the following
Hence ideally your prog ought to have been
Exception handling is a feature which allows the programmer to take corrective action and continue with the program. For example lets assume Iam reading from a file and displaying contents. When the file's not found I read from a default file.
In your program, all you could/should do is exit if the account no is invalid.