一、键盘录入数据
import java.text.ParseException;
import java.util.InputMismatchException;
import java.util.Scanner;public class Co {public static void main(String[] args) throws ParseException {//键盘录入信息int age=0;String name=null;Scanner sc = new Scanner(System.in);boolean flag = true;while (flag) {try {System.out.println("输入姓名: ");name = sc.nextLine();checkname(name);flag = false;} catch (RuntimeException e) {System.out.println("姓名长度有误");}}System.out.println("姓名符合规则");flag = true;while (flag) {try {System.out.println("输入年龄:");String temp = sc.nextLine();age=Integer.parseInt(temp);checkage(age);flag=false;} catch (InputMismatchException | NumberFormatException e) {System.out.println("输入整数年龄");} catch (NullPointerException e) {System.out.println("年龄大小不合规矩");}}System.out.println("年龄和规矩");System.out.println("姓名为: "+name+",年龄为: "+age);}public static void checkname (String name){if (name.length() > 10 || name.length() < 3)throw new RuntimeException();}public static void checkage ( int age){if (age < 18 || age > 40)throw new NullPointerException();}
}
自定义异常:
public class NameformatException extends RuntimeException{//Nameformat:异常的名字//Exception:表示当前是一个异常类//运行时异常继承 RuntimeException 核心:表示由参数有异常导致的问题//编译时异常继承 Exception 核心:提醒程序员检查本地信息//空参构造+带参构造 alt+insertpublic NameformatException() {}public NameformatException(String message) {super(message);}
}
public class AgeformatExcetion extends RuntimeException{public AgeformatExcetion() {}public AgeformatExcetion(String message) {super(message);}
}
import java.text.ParseException;
import java.util.InputMismatchException;
import java.util.Scanner;public class Co {public static void main(String[] args) throws ParseException {//键盘录入信息int age=0;String name=null;Scanner sc = new Scanner(System.in);boolean flag = true;while (flag) {try {System.out.println("输入姓名: ");name = sc.nextLine();checkname(name);flag = false;} catch (NameformatException e) {System.out.println("姓名长度有误");}}System.out.println("姓名符合规则");flag = true;while (flag) {try {System.out.println("输入年龄:");String temp = sc.nextLine();age=Integer.parseInt(temp);checkage(age);flag=false;} catch (InputMismatchException | NumberFormatException e) {System.out.println("输入整数年龄");} catch (AgeformatExcetion e) {System.out.println("年龄大小不合规矩");}}System.out.println("年龄和规矩");System.out.println("姓名为: "+name+",年龄为: "+age);}public static void checkname (String name){if (name.length() > 10 || name.length() < 3)throw new NameformatException();}public static void checkage ( int age){if (age < 18 || age > 40)throw new AgeformatExcetion();}
}