模拟斗地主、异常、抛出异常throw、声明异常throws、常用方法、自定义异常

模拟斗地主思路图

根据这个图来构思 
package
com.oracle.demo01; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Map; //模拟斗地主 public class DouDiZhu { public static void main(String[] args) { //1.创建扑克牌map Map<Integer,String> pooker=new HashMap<Integer,String>(); //创建所有key所在的容器 ArrayList<Integer> pookerNum=new ArrayList<Integer>(); //创建花色数组 String[] color={"黑桃","红桃","放屁","梅花"}; //创建牌号数组 String[] number={"2","A","K","Q","J","10","9","8","7","6","5","4","3"}; //造牌并存进map集合 int index=2; //先遍历数字 for(String n:number){ //在遍历花色 for(String c:color){ //向map中存数据 pooker.put(index,c+n); //向所有key所在的容器存数据 pookerNum.add(index); index++; } } //System.out.println(pooker); //把大王存进去 pooker.put(0,"大王"); pookerNum.add(0); //把小王存进去 pooker.put(1,"小王"); pookerNum.add(1); //用 collections洗牌 Collections.shuffle(pookerNum); System.out.println(pookerNum); //发牌 需要创建四个容器 ArrayList<Integer> bottom=new ArrayList<Integer>(); ArrayList<Integer> player1=new ArrayList<Integer>(); ArrayList<Integer> player2=new ArrayList<Integer>(); ArrayList<Integer> player3=new ArrayList<Integer>(); //发牌 用for循环遍历 for(int i=0;i<pookerNum.size();i++){ //将前三张牌给底牌 if(i<3){ bottom.add(pookerNum.get(i)); }else if(i%3==0){ player1.add(pookerNum.get(i)); }else if(i%3==1){ player2.add(pookerNum.get(i)); }else if(i%3==2){ player3.add(pookerNum.get(i)); } } //把三个玩家牌给排序:排的是4个容器的排序 Collections.sort(bottom); Collections.sort(player1); Collections.sort(player2); Collections.sort(player3); //看牌 look("刘德华",player1,pooker); look("渣渣辉",player2,pooker); look("阿斯蒂芬",player3,pooker); look("底牌",bottom,pooker); } //看牌的方法 传 玩家 字典 排 public static void look(String name,ArrayList<Integer> player,Map<Integer,String> pooker){ //打印玩家姓名 System.out.print(name+":"); //遍历所有牌号 增强for for(int num:player){ System.out.print(pooker.get(num)+" "); } System.out.println(); } }

异常

Java代码在运行时期发生的问题就是异常

异常的继承体系 Exception类来描述异常

Exception还有个兄弟 Error (错误)

区别:Exception能救   Error

异常继承体系总结:

     Throwable:错误与异常的超类(祖宗类)

① Error 错误

②  Exception 编译异常

 2.1 RuntimeException 子类 运行异常

  异常与错误的区别

 异常:程序编译、运行期间发生的某种异常(XxxException),对异常进行具体的处理。若不处理,程序结束运行

 错误:程序在运行期间发生了某种错误(XxxError),Error错误通常没有具体的处理方式,程序将会结束运行。Error错误是系统级别问题,都是jvm所在系统发生的,并反馈给jvm的。无法针对处理,只有改代码

 异常的产生过程解析

 

JAVA常见异常
异常类 说明
ClassCastException 类型转换异常
ClassNotFoundException 未找到相应类异常
ArithmeticException 算数异常
ArrayIndexOutOfBoundsException 数组下标越界异常
ArrayStoreException 数组中包含不兼容的值抛出异常
SQLException 操作数据库异常类
NullPointerException 空指针异常
NoSuchFieldException 字段未找到异常
NoSuchMethodException 方法未找到抛出的异常
NumberFormatException 字符串转数字抛出的异常
NegativeArraySizeException 数组元素个数为负数抛出异常
StringIndexOutOfBoundsException 字符串索引超出范围抛出异常
IOException 输入输出异常
IllegalAccessException 不允许访问某类异常
InstantiationException 应用程序试图使用Class类中的newInstance()方法创建一个类的实例,指定类对象无法被实例化
EOFException 文件结束
FileNotFoundException 文件未找到
   
RuntimeException异常
种类 说明
NullPointerException 空指针
ArrayIndexOutOfBoundsException 数组下标
ArithmeticException 算术
ArrayStoreException 数组中包含不兼容的值
IllegalArgumentException 非法参数
SecurityException 安全性
NegativeArraySizeException 数组长度为负


pm

抛出异常 throw  

格式:throw new 异常类名(参数);

 

声明异常  throws

声明异常格式:修饰符  返回值类型 方法名(参数) throws 异常类名1,异常类名2...{}

package com.oracle.demo01;
//抛出异常  throw 和 throws的用法
public class Throw {
    public static void main(String[] args) throws Exception{
        //定义数组
        int[] arr=null;
        //调用方法
        int a=get(arr);
        System.out.println(a);
    }
    public static int get(int[] arr) throws Exception{
        //如果arr为空
        if(arr==null){
            //抛出异常
            throw new Exception("数组为空");
        }
   if(arr.length==0){
            throw new Exception("数组长度为0");
//取下标 int i =arr[arr.length-1]; return i; } }

处理方式:

① 虚拟机处理  throws

②  try...catch   (自己处理的会显示 )

捕获异常try…catch…finally

捕获:Java中对异常有针对性的语句进行捕获,可以对出现的异常进行指定方式的处理

格式:

try {

     //需要被检测的语句。

}

catch(异常类 变量) { //参数。

     //异常的处理语句。

}

finally {

     //一定会被执行的语句。

}

try可能产生异常的代码。

catch异常捕获,对捕获到的异常处理

finally有无异常都要执行。如果因为异常导致程序跳转,有些代码无法执行,finally专治此问题,finally代码块的代码必须执行

class ExceptionDemo{
    public static void main(String[] args){ //throws ArrayIndexOutOfBoundsException
         try {
              int[] arr = new int[3];
            System.out.println( arr[5] );// 会抛出ArrayIndexOutOfBoundsException
            当产生异常时,必须有处理方式。要么捕获,要么声明。
        }
        catch (ArrayIndexOutOfBoundsException e) { //括号中需要定义什么呢?try中抛出的是什么异常,在括号中就定义什么异常类型。
            System.out.println("异常发生了");
        } finally {
              arr = null; //把数组指向null,通过垃圾回收器,进行内存垃圾的清除
}
         System.out.println("程序运行结果");
    }
}

  try…catch…finally异常处理的组合方式

 try catch finally组合检测异常,并传递给catch处理,并在finally中进行资源释放

 try catch组合 : 对代码进行异常检测,并对检测的异常传递给catch处理。对异常进行捕获处理

 一个try 多个catch组合 : 对代码进行异常检测,并对检测的异常传递给catch处理。对每种异常信息进行不同的捕获处理

try finally 组合: 对代码进行异常检测,检测到异常后因为没有catch,所以一样会被默认jvm抛出。异常是没有捕获处理的。但是功能所开启资源需要进行关闭,所有finally。只为关闭资源

运行时期异常

RuntimeException和他的所有子类异常,都属于运行时期异常

NullPointerException,ArrayIndexOutOfBoundsException等都属于运行时期异常

特点:

运行时期异常,方法定义中无需throws声明,调用者也无需处理此异常  ②运行期发生异常,改代码

异常在方法重写中细节

注意:

1 子类重写父类方法要抛出和父类一样的异常,要么不抛出

2 。。。。。。。。抛出的异常不能超过父类的范围(不能越界)

如果父类没抛 子类想抛 只能调try...catch

异常中常用方法

package com.oracle.demo01;
//异常中常用方法
public class Throw3 {
    public static void main(String[] args) throws Exception{
        //定义数组
        int[] arr=null;
        //可能会发生异常的语句
        try{
            //调用方法
            int a=get(arr);
            System.out.println(a);
        }catch(Exception ex){
            //getMessage()只打印异常信息
            //System.out.println(ex.getMessage());//不常用
            //toString()打印异常对象和异常信息
            //System.out.println(ex.toString());
            //printStackTrace()以红字的方式打印异常对象、信息、位置
            ex.printStackTrace();
        }finally{
            //不管发不发生异常都要执行的语句
            System.out.println("finally执行了");
        }        
    }
    public static int get(int[] arr) throws NullPointerException,ArrayIndexOutOfBoundsException{
        //如果arr为空
        if(arr==null){
            //抛出异常
            throw new NullPointerException("数组为空");
        }
        if(arr.length==0){
            throw new ArrayIndexOutOfBoundsException("数组长度为0");
        }
        //取下标
        int i =arr[arr.length-1];
        return i;
    }
}

getMessage():返回该异常的详细信息字符串,即异常提示信息

toString():返回该异常的名称与详细信息字符串

printStackTrace():在控制台输出该异常的名称与详细信息字符串异常出现的代码位置

自定义异常类的定义

 格式

Class 异常名 extends Exception{ //或继承RuntimeException 

     public 异常名(){ 

}

     public 异常名(String s){

 super(s);

 }

 }

先确定RunTimeException时期还是非运行时期异常 

package com.oracle.demo01;
//自定义异常类  
public class Zi定义异常类 {
    public static void main(String[] args) {
        //定义一个数组
        int[] arr={7,8,9,4,5,6,-9};
        double num=avg(arr);
        System.out.println(num);
    }
    //写一个方法求平均数
    public static double avg(int[] arr){
        //自已计数器
        int sum=0;
        for(int i:arr){
            //加个判断
            if(i<0){
                throw new FuShuException("负数异常"+i);
            }
            sum+=i;
        }
        //数组长度
        return sum/arr.length;
    }
}
-----------------------------------------------------
package com.oracle.demo01;

public class FuShuException extends RuntimeException{
    public FuShuException(String s){
        //传父类
        super(s);
    }
}

 

原文地址:https://www.cnblogs.com/zs0322/p/10958728.html