1.异常
自定义异常类:MyException
package org.jsoft.zuoye;
import java.io.IOException;
import java.sql.SQLException;
public class MyException extends Exception{
// 禁止未满18周岁的人进网吧,自定义异常
public MyException(){
super("未满18岁禁止入内!");
}
}
测试类:TestMyException
package org.jsoft.zuoye;
import java.io.IOException;
import java.sql.SQLException;
public class TestMyException {
public static void main(String[] args) {
try {
checkAge(20);
checkAge(12);
} catch (MyException e) {
e.printStackTrace();
}finally{
System.out.println("无论异常是否发生,此代码都执行");
}
}
public static void checkAge(int age) throws MyException{
if(age<18){
throw new MyException();
}else{
System.out.println("欢迎光临");
}
}
}
2.判断你和你同桌是不是一个人? 以及以字符串形式显示人的基本信息
package org.jsoft.zuoye;
class Student{//学生类,用来保存我和同桌的信息
private String name;
private int age;
private String major;
public Student(String name,int age,String major){
this.name=name;
this.age=age;
this.major=major;
}
public String toString(){//重写toString类
return "姓名:"+this.name+",年齡:"+this.age+",专业:"+this.major;
}
public boolean equals(Object ob){//判断两个类是否相等
if(ob==null){
return false;
}else{
if(ob instanceof Student){
Student stu=(Student)ob;
if(this.name.equals(stu.name)&&this.age==stu.age&&this.major.equals(stu.major)){
return true;
}
}
}
return false;
}
}
public class TestObject {
public static void main(String[] args) {
Student s1 = new Student("袁现程",20,"计算机");
Student s2 = new Student("张城玮",21,"计算机");
System.out.println("我和我同桌是不是一个人?");
System.out.print("当然");
System.out.println(s1.equals(s2));
System.out.println(s1);
System.out.println(s2);
}
}