您的位置:首页 > 编程语言 > Java开发

Java复习笔记[3] —— 数组,函数,异常处理

2017-03-12 21:43 357 查看


数组:
声明:elementType[]
array; 或elementType array[];(不推荐)
创建数组:elementType[]
array = new elementType[arraySize];
创建并初始化:elementType[]
array = { value0, value1, value2, … , value N }

多维数组,数组传参,数组作为返回值举例:

public class ArrayDemo {
    private int[][] table;

    
    public ArrayDemo(int size) {
        table = new int[size][size];
        for (int i = 0; i < size; i++) {
            table[i][0] = i + 1;
            table[0][i] = i + 1;

        }
        for (int i = 1; i < size; i++) {
            for (int j = 1; j < size; j++) {
                table[i][j] = table[i-1][j] + table[i][j-1];

            }

        }

    }

    
    public void showTable() {
        ArrayDemo.printTable(table);

    }

    
    public static void printTable(int[][] ta) {
        int ySize = ta.length;
        int xSize = ySize > 0 ? ta[0].length : 0;
        for (int i = 0; i < ySize; i ++) {
            for (int j = 0; j < xSize; j++) {
                System.out.printf("%-6d", ta[i][j]);

            }
            System.out.println();

        }

    }

    
    public int[][] subTable(int x1, int y1, int x2, int y2) {
        int minX = x1 < x2 ? x1 : x2;
        int minY = y1 < y2 ? y1 : y2;
        int maxX = x1 < x2 ? x2 : x1;
        int maxY = y1 < y2 ? y2 : y1;
        int xLen = maxX-minX+1;
        int yLen = maxY-minY+1;
        int[][] sTable = new int[yLen][xLen];
        for (int i = 0; i < yLen; i++) {
            for (int j = 0; j < xLen; j++) {
                sTable[i][j] = table[i+minY-1][j+minX-1];

            }

        }
        return sTable;

    }

}
main:
ArrayDemo ad = new ArrayDemo(9);

ad.showTable();
System.out.println();
ArrayDemo.printTable(ad.subTable(4, 6, 8, 3));
输出:

1     2     3     4     5     6     7     8     9     
2     4     7     11    16    22    29    37    46    
3     7     14    25    41    63    92    129   175   
4     11    25    50    91    154   246   375   550   
5     16    41    91    182   336   582   957   1507  
6     22    63    154   336   672   1254  2211  3718  
7     29    92    246   582   1254  2508  4719  8437  
8     37    129   375   957   2211  4719  9438  17875 
9     46    175   550   1507  3718  8437  17875 35750 
25    41    63    92    129   
50    91    154   246   375   
91    182   336   582   957   
154   336   672   1254  2211  
 

Arrays类的静态方法:

需要引用包:java.util.Arrays

方法
描述
int binarySearch(Object[] a, Object key)
用二分查找算法在给定数组中搜索给定值的对象(Byte,Int,double等)。数组在调用前必须排序好的。如果查找值包含在数组中,则返回搜索键的索引;否则返回 - 1
boolean equals(long[] a, long[] a2)
如果两个指定的 long 型数组彼此相等,则返回 true。如果两个数组包含相同数量的元素,并且两个数组中的所有相应元素对都是相等的,则认为这两个数组是相等的。换句话说,如果两个数组以相同顺序包含相同的元素,则两个数组是相等的。同样的方法适用于所有的其他基本数据类型(Byte,short,Int等)
void fill(int[] a, int val)
将指定的 int 值分配给指定 int 型数组指定范围中的每个元素。同样的方法适用于所有的其他基本数据类型(Byte,short,Int等)
void sort(Object[] a)
对指定对象数组根据其元素的自然顺序进行升序排列。同样的方法适用于所有的其他基本数据类型(Byte,short,Int等)
 
函数 &方法:

定义:

修饰符 返回值类型 方法名(参数类型 参数名) {

    ...

    方法体

    ...

    return 返回值;

}
方法重载:

方法名称相同,参数类型或者数量不同的方法即可重载原方法(返回值类型不同不能表示重载)

 

可变参数:

一个方法中最多只能有一个可变参数,如果指定了可变参数,则必须是参数列表中的最后一个参数,可变参数示例:

public class FuncDemo {
    public void printTotal(int... nums) {
        int total = 0;
        for (int i : nums) {

            total += i;

        }

        
        System.out.println(total);

    }

}

 

Main:
FuncDemo fd = new FuncDemo();
fd.printTotal(10, 8, 40, 20, 1, 4, 9);
输出:

92
 

类的构造方法和析构方法(Finalize):

public class ClassDemo {
    int prop;

    
    ClassDemo() {
        System.out.println("Default constructor");

    }

    
    ClassDemo(int para) {
        System.out.println("Self defined constructor");

        prop = para;

    }

    
    protected void finalize() {
        System.out.println("Deconstructor");

    }

}

 

Main:
ClassDemo c1 = new ClassDemo();
ClassDemo c2 = new ClassDemo(10);
c1 = c2 = null;
System.gc();
输出:

Default constructor

Self defined constructor

Deconstructor

Deconstructor
 

异常处理:

所有的异常类都是从 java.lang.Exception类继承的子类。Exception类是
Throwable类的子类。除了Exception类外,Throwable还有一个子类Error。Java程序通常不捕获错误。错误一般发生在严重故障时,它们在Java程序处理的范畴之外。Error用来指示运行时环境发生的错误。一般地,程序不会从错误中恢复。异常类有两个主要的子类:IOException类和RuntimeException类。

Java中的非检查性异常:

异常
描述
ArithmeticException
当出现异常的运算条件时,抛出此异常。例如,一个整数"除以零"时,抛出此类的一个实例。
ArrayIndexOutOfBoundsException
用非法索引访问数组时抛出的异常。如果索引为负或大于等于数组大小,则该索引为非法索引。
ArrayStoreException
试图将错误类型的对象存储到一个对象数组时抛出的异常。
ClassCastException
当试图将对象强制转换为不是实例的子类时,抛出该异常。
IllegalArgumentException
抛出的异常表明向方法传递了一个不合法或不正确的参数。
IllegalMonitorStateException
抛出的异常表明某一线程已经试图等待对象的监视器,或者试图通知其他正在等待对象的监视器而本身没有指定监视器的线程。
IllegalStateException
在非法或不适当的时间调用方法时产生的信号。换句话说,即 Java
环境或 Java 应用程序没有处于请求操作所要求的适当状态下。
IllegalThreadStateException
线程没有处于请求操作所要求的适当状态时抛出的异常。
IndexOutOfBoundsException
指示某排序索引(例如对数组、字符串或向量的排序)超出范围时抛出。
NegativeArraySizeException
如果应用程序试图创建大小为负的数组,则抛出该异常。
NullPointerException
当应用程序试图在需要对象的地方使用 null 时,抛出该异常
NumberFormatException
当应用程序试图将字符串转换成一种数值类型,但该字符串不能转换为适当格式时,抛出该异常。
SecurityException
由安全管理器抛出的异常,指示存在安全侵犯。
StringIndexOutOfBoundsException
此异常由 String 方法抛出,指示索引或者为负,或者超出字符串的大小。
Java中的检查性异常:

异常
描述
ClassNotFoundException
应用程序试图加载类时,找不到相应的类,抛出该异常。
CloneNotSupportedException
当调用 Object 类中的 clone 方法克隆对象,但该对象的类无法实现 Cloneable 接口时,抛出该异常。
IllegalAccessException
拒绝访问一个类的时候,抛出该异常。
InstantiationException
当试图使用 Class 类中的 newInstance 方法创建一个类的实例,而指定的类对象因为是一个接口或是一个抽象类而无法实例化时,抛出该异常。
InterruptedException
一个线程被另一个线程中断,抛出该异常。
NoSuchFieldException
请求的变量不存在
NoSuchMethodException
请求的方法不存在
Throwable类的相关方法:

方法
说明
public String getMessage()
返回关于发生的异常的详细信息。这个消息在Throwable
类的构造函数中初始化了。
public Throwable getCause()
返回一个Throwable 对象代表异常原因。
public String toString()
使用getMessage()的结果返回类的串级名字。
public void printStackTrace()
打印toString()结果和栈层次到System.err,即错误输出流。
public StackTraceElement [] getStackTrace()
返回一个包含堆栈层次的数组。下标为0的元素代表栈顶,最后一个元素代表方法调用堆栈的栈底。
public Throwable fillInStackTrace()
用当前的调用栈层次填充Throwable 对象栈层次,添加到栈层次任何先前信息中。
try…catch…finally,throw关键字,自定义异常,方法检查性异常定义(throws)使用示例:

MyException.java:
public class MyException extends Exception {
    public String toString() {
        return "This is my exception";

    }

}

 

MyRuntimeException.java:
public class MyRuntimeException extends RuntimeException {
    public String toString() {
        return "This is my runtime exception";

    }

}

 

ExceptionDemo.java:
public class ExceptionDemo {
    public void TryCatchDemo(int choice) {
        try

        {
            switch (choice) {
                case 1:

                    throwMyException();
                case 2:

                    throwMyRuntimeException();
                case 3:
                    throwTwoKindsOfExceptions(true);
                case 4:
                    throwTwoKindsOfExceptions(false);
                default:
                    ClassDemo c = null;
                    c.toString();   // throws NullPointerException

            }
        } catch (MyException e) {
            System.out.println(e.toString());
        } catch (MyRuntimeException e1) {
            System.out.println(e1.toString());
        } catch (Exception e2) {
            System.out.println(e2.toString());
        } finally {
            System.out.println("Finally...");

        }

    }

    
    public void throwMyException() throws MyException {
        throw new MyException();

    }

    
    public void throwMyRuntimeException() throws MyRuntimeException {
        throw new MyRuntimeException();

    }

    
    public void throwTwoKindsOfExceptions(boolean choice) throws MyException, MyRuntimeException {
        if (choice) {
            throw new MyException();
        } else {
            throw new MyRuntimeException();

        }

    }

}

 

Main.java:
ExceptionDemo ed = new ExceptionDemo();
ed.TryCatchDemo(1);
ed.TryCatchDemo(2);
ed.TryCatchDemo(3);
ed.TryCatchDemo(4);
ed.TryCatchDemo(5);
输出:

This is my exception

Finally...

This is my runtime exception

Finally...

This is my exception

Finally...

This is my runtime exception

Finally...

java.lang.NullPointerException

Finally...
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息