我被要求编写一段程序来使用 try 和 catch 处理异常。虽然,当我运行它时,它不会反映我的异常代码,因为应该打印“无效名称”。有人能指出原因吗?如果有人更正我的代码也将非常受欢迎!谢谢。
我需要在以下条件下编写一个程序:
导入 javax.naming.InvalidNameException。编写一个方法 public void printName(String name) throws InvalidNameException 如果 name 没有空格,该方法应该抛出一个 InvalidNameException。编写驱动程序进行测试。
===============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");
}
}
}