一、异常
package org.jsoft.homework;
import java.sql.SQLException;
public class TestException{
public static void main(String[] args) {
try {
a.p();//静态方法直接用类调用。
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace(); //打印捕获的异常
}catch(ClassCastException e){
System.out.println(e.getMessage());//在控制台输出捕获异常的信息
}
}
}
class a{
public static void p1(int num) throws ClassCastException{//抛出ClassCast……异常
if (num>=3){
throw new ClassCastException("不能再吃了!");//捕到异常时显示的信息
}
}
public static void p2(String s) throws SQLException//抛出SQL……异常
{
if(s.equals("没有")){
throw new SQLException("抓紧时间学习吧!");//捕到异常时显示的信息
}
}
public static void p() throws ClassCastException,SQLException{//抛出两个异常
System.out.println("今天吃了3顿饭");
p1(3);//调用本类p1的方法。传递的实参为3
System.out.println("今天还没有学习!");
p2("没有");//调用本类p2的方法,传递的实参为没有
}
}
执行时遇到了点问题:只能捕获到一个异常。
捕获到了第一个异常后,下面的语句就不会执行。
下面就是第一个正常,第二个有异常。
二、判断
//学生类
package org.jsoft.homework;
public class Student {
private String name;
private int age;
public void setName(String name){
this.name=name;
}
public String getName (){
return name;
}
public void setAge(int age){
this.age=age;
}
public int getAge(){
return age;
}public Student(){ }
public Student(String name, int age){
this.name=name;
this.age=age;
}
public String toString() {
return name+" "+age;
}
}
//判断类
package org.jsoft.homework;
public class PanDuan {
static Student s=new Student("小明",18);//因为 main 要调用s 的方法 所以要写成静态
static Object o=new Student("小红",18);//同理
public static void main(String[] args) {
PanDuan pd=new PanDuan();//声明并实例化本类的对象
System.out.println("两个人名字是否相同:"+pd.equals(o));//调用本类中的equals方法
System.out.println("两个人年龄是否相同:"+pd.equals_1(o));//调用本类中的equals_1方法
System.out.println("两个人是否为同一个人:"+pd.equals_2(o));//调用本类中的equals_2方法
System.out.println(s.toString());//输出Student的toString 语句
System.out.println(o.toString());//输出Student的toString 语句
}
public boolean equals(Object o){//判断俩个人名字是否相同的方法体
if(o==null){
return false;
}else{
if(o instanceof Student){//判断o是否为Student类型
Student s1=(Student)o;//将o转换成Student类型
if(s1.getName()==s.getName()){//判断名字是否相同的语句
return true;
}
}
}return false;
}public boolean equals_1(Object o){//判断年龄是否相等的方法体
if(o==null){
return false;
}else{
if (o instanceof Student){//判断o 是不是Student类型
Student s1=(Student )o;//将o转换成Student类型
if(s1.getAge()==s.getAge()){//判断年龄是否相等的语句
return true;
}
}}
return false;
}public boolean equals_2(Object o){//判断两个人是否为同一个人的方法体
if(o==null)
{return false;
}else{
if(o instanceof Student){//判断o 是否为Student类型
Student s1=(Student )o;//将o 转换成Student类型
if(s1.getName()==s.getName()&&s1.getAge()==s.getAge()){//判断两个人是否为同一个人的语句
return true;
}
}
}
return false;
}
}
将 两个名字都改成小明
一下为控制台输出的语句