...
Locate and open the project from the last exercise -
EmployeeMavenProj
EmployeeProj
.Create a new class
EmployeeFileMain
for this task. Give it amain()
method.Define a static method in the same class - call it
getInput()
. This method will be responsible for interacting with the user. It should take oneString
parameter - a question to print out. It should read the answer from the terminal - declare and create anInputStreamReader
usingSystem.in
as its constructor parameter.Code Block language java InputStreamReader isr = new InputStreamReader(System.in);
Similarly, declare and create a
BufferedReader
using yourInputStreamReader
reference as its constructor argument. Use thereadLine()
method ofBufferedReader
to retrieve your keyboard input - that is theString
the method should return. ThereadLine()
method is declared to throw anIOException
. We have two choices - either we wrap the call to thereadLine()
method withintry
block and declare acatch
block, or we pass the buck. We will opt for the latter - declare yourgetInput()
method as throwingIOException
.Declare new
static
method: aninputEmployee()
method which will ask for a new employee's details to be entered. FrominputEmployee()
callgetInput()
three times - first ask for the first name and store the returned value in a variablenfame
. Secondly, ask for the last name - store the return value inlname
. Then ask for the age and store the returned value in variablestrAge
. Convert this value to anint
using static methodInteger.parseInt()
and store in the variable calledage
.Create an
Employee
object passing the three values into its constructor - you may need to create the constructor first!We need to handle the exception that may be thrown in the
getInput()
method. We will pass the buck again - declare yourinputEmployee()
method as throwingIOException
. Now it will need to be handled in themain
method - there is no other option.Within your
main
method, make a call toinputEmployee
method - you will see that it won't compile. The call needs to be withintry
block and we need to providecatch
block and capture theIOException
. Print out a message that something went wrong.Code Block language java try{ inputEmployee() }catch(IOException e){ System.out.println("Problem occurred.") }
Now run the application supplying the name and a numeric age.
Run the application again but supply non-numeric age -i.e.
abc
. The application with crash since it can't castabc
into anint
. You will see a stack trace fromNumberFormatException
.Let’s handle that exception. Declare the
inputEmployee
method as throwingNumberFormatException
, in themain
method include anothercatch
block to handle it. Make it printCode Block language java e.getMessage() + " is an invalid age!"
Run your application again and make sure it can handle non-numeric data.
...