I am asked to write a piece of program to handle exception using try and catch. Although, when I ran it, it would not have reflected my exception codes as "invalid name" should have printed. Can anybody point the reason out? If someone corrects my code would be big welcome as well! Thanks.
I need write a program under the following conditions :
import javax.naming.InvalidNameException. Write a method public void printName(String name) throws InvalidNameException If name has no white space the method should throw an InvalidNameException. Write a driver to test.
===============Code result=============
Enter your name: James Dean
First name: James
Last name: Dean
Enter your name: Brian Smith
First name: Brian
Last name: Smith
Enter your name: RuthKnight
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at Name.printName(Name.java:33)
at NameApp.main(NameApp.java:17)
==================Method============================
import javax.naming.InvalidNameException;
public class Name{
public void printName(String name) throws InvalidNameException{
String [] nameSplit = name.split(" ");
String first = nameSplit[0];
String last = nameSplit[1];
System.out.println("First name: "+first);
System.out.println("Last name: "+last);
}
}
======================Driver========================
import java.util.Scanner;
import javax.naming.InvalidNameException;
public class NameApp{
public static void main(String[] args) {
Name aa = new Name();
Scanner console = new Scanner(System.in);
try {
boolean keepRunning= true;
while(keepRunning){
System.out.print("Enter your name: ");
String in = console.nextLine();
aa.printName(in);
}
}
catch(InvalidNameException e){
System.out.println("invalid name");
}
}
}