2019.11.23 Java小结

1.Java常用类

  • Arrays
  • StringBuilder
  • Math
  • System
  • Random

1.1 Arrays常用方法

package MyTest;
import java.util.*;
public class ArraysDemo {
	public static void main(String[]args)
	{
		int[]arr=new int[10];
		//将数组元素都设为9
		Arrays.fill(arr, 9);
		System.out.println("fill:"+Arrays.toString(arr));
		
		Random random=new Random();
		for(int i=0;i<arr.length;i++) {
			//使用100以内的随机数赋值数组
			arr[i]=random.nextInt(101);
		}
		//打印重新赋值后的数组
		System.out.println("Reinit:"+Arrays.toString(arr));
		//将索引为5的元素设为50
		arr[5]=50;
		//排序
		Arrays.sort(arr);
		System.out.println("after sort"+Arrays.toString(arr));
		int i=Arrays.binarySearch(arr, 50);
		System.out.println("where is 50?"+i);
		//复制一份新数组
		int []newArr=Arrays.copyOf(arr, arr.length);
		//比较
		System.out.println("equals:"+Arrays.equals(arr, newArr));
		
	}
}

1.2 StringBuilder常用方法

package MyTest;
import java.util.*;
public class StringBuilderTest {
	public static void main(String[]args) {
		StringBuilder s=new StringBuilder("I");
		System.out.println(s);
		s.append(" java");
		System.out.println("s");
		s.insert(1, " love");
		System.out.println(s);
		String t=s.toString();
		System.out.println(t);
		s.reverse();
		System.out.println(s);
		s.delete(1, 3);
		System.out.println(s);
		s.replace(1, 3, "!!!");
		System.out.println(s);
	}
}

1.3 Math常用方法

public class MathDemo {
    public static void main(String[] args) {
        System.out.println(Math.abs(-12.7));
        System.out.println(Math.ceil(12.7));
        System.out.println(Math.rint(12.4));
        System.out.println(Math.random());
        System.out.println("sin30 = " + Math.sin(Math.PI / 6));
        // 计算30°的正弦值,参数是用弧度表示的角,即π的六分之一
        System.out.println("cos30 = " + Math.cos(Math.PI / 6));
        // 计算30°的余弦值,这些计算三角函数的方法,其参数和返回值的类型都为double
        System.out.println("tan30 = " + Math.tan(Math.PI / 6));
        // 计算30°的正切值
    }
}

1.4 System常用方法

package MyTest;
import java.util.*;
public class SystemDemo {
	public static void main(String[]args) {
		int[]a= {7,8,9,10,11};
		int[]b= {1,2,3,4,5,6};
		System.arraycopy(a, 1, b, 2, 3);
		
		System.out.println(Arrays.toString(b));
		System.out.println("current:"+System.currentTimeMillis());
		System.out.println("javaVersion:"+System.getProperty("java.version"));
		System.out.println("javaHome:"+System.getProperty("java.home"));
		System.gc();
		System.exit(0);
	}
}

1.5 Random常用方法

package MyTest;
import java.util.*;
public class RandomDemo {
	public static void main(String[]args) {
		Random random=new Random();
		Scanner in=new Scanner(System.in);
		int m=in.nextInt();
		int n=in.nextInt();
		System.out.println(random.nextInt(n-m+1)+m);
	}
}

这里要学习一下输入n,m和输出(n,m)区间的随机数写法^_^

2.异常

  • 异常分类
  • 声明及抛出
  • 捕获异常
  • 自定义异常
  • 异常堆栈

异常指不期而至的各种状况,它在程序运行的过程中发生。作为开发者,我们都希望自己写的代码永远都不会出现bug,然而现实告诉我们并没有这样的情景。如果用户在程序的使用过程中因为一些原因造成他的数据丢失,这个用户就可能不会再使用该程序了。所以,对于程序的错误以及外部环境能够对用户造成的影响,我们应当及时报告并且以适当的方式来处理这个错误。

之所以要处理异常,也是为了增强程序的鲁棒性

异常都是从Throwable类派生出来的,而Throwable类是直接从Object类继承而来。你可以在 Java SE 官方 API 文档中获取更多关于它们的知识。

2.1 异常分类

异常通常有四类:

  • Error:系统内部错误,这类错误由系统进行处理,程序本身无需捕获处理
  • Exception:可以处理的异常
  • RuntimeException:可以捕获,也可以不捕获的异常
  • 继承 Exception 的其他类:必须捕获,通常在 API 文档中会说明这些方法抛出哪些异常

平时主要关注的异常是 Exception 下的异常,而 Exception 异常下又主要分为两大类异常,一个是派生于 RuntimeExcption 的异常,一个是除了 RuntimeExcption 体系之外的其他异常。

RuntimeExcption 异常(运行时异常)通常有以下几种:

  • 错误的类型转换
  • 数组访问越界
  • 访问 null 指针
  • 算术异常

一般来说,RuntimeException 都是程序员的问题。

非 RuntimeException(受查异常)一般有:

  • 打开一个不存在的文件
  • 没有找到具有指定名称的类
  • 操作文件异常

受查异常是编译器要求必须处理的异常,必须使用 try catch 处理,或者向上抛出,给上层处理。

2.2 声明及抛出

throw 抛出异常

当程序运行时数据出现错误或者我们不希望发生的情况出现的话,可以通过抛出异常来处理。

public class ThrowTest {

    public static void main(String[] args) {
        Integer a = 1;
        Integer b = null;
        //当a或者b为null时,抛出异常
        if (a == null || b == null) {
            throw new NullPointerException();
        } else {
            System.out.println(a + b);
        }
    }

throws 声明异常

throws 用于声明异常,表示该方法可能会抛出的异常。如果声明的异常中包括 checked 异常(受查异常),那么调用者必须处理该异常或者使用 throws 继续向上抛出。throws 位于方法体前,多个异常使用,分割。

package MyTest;
import java.io.*;
public class ThrowTest {
	public static void main(String[]args) throws FileNotFoundException{
		throwsTest();
	}
	public static void throwsTest() throws FileNotFoundException{
		new FileInputStream("/home/project/shiyanlou.txt");
	}
}

2.3 捕获异常

通常抛出异常后,还需要将异常捕获。使用trycatch语句块来捕获异常,有时候还会用到finally

对于上述三个关键词所构成的语句块,try语句块是必不可少的,catchfinally语句块可以根据情况选择其一或者全选。你可以把可能发生错误或出现问题的语句放到try语句块中,将异常发生后要执行的语句放到catch语句块中,而finally语句块里面放置的语句,不管异常是否发生,它们都会被执行。

你可能想说,那我把所有有关的代码都放到try语句块中不就妥当了吗?可是你需要知道,捕获异常对于系统而言,其开销非常大,所以应尽量减少该语句块中放置的语句。

package MyTest;
import java.io.*;
public class CatchException {
	public static void main(String[]args) {
		try {
			System.out.println("TryBlock");
			//声明一个空的class对象用于引发“类未发现异常”
			Class<?> tempClass=Class.forName("");
			System.out.println("Bye TryBlock");
		}catch(ClassNotFoundException e) {
			System.out.println("I'm CatchBlock");
			e.printStackTrace();
			System.out.println("GoodBye!CatchBlock");
		}finally {
			System.out.println("I'm finally block");
		}
	}
}

2.3.1 捕获多个异常

package MyTest;
import java.io.*;
public class MultipleCapturesDemo {
	public static void main(String[]args) {
		try {
			new FileInputStream("");
		}catch(FileNotFoundException e) {
			System.out.println("IO Exception!");
		}catch(Exception e) {
			System.out.println("Exception!");
		}
	}
}

在处理异常时,并不要求抛出的异常同 catch 所声明的异常完全匹配,子类的对象也可以匹配父类的处理程序。比如异常 A 继承于异常 B,那么在处理多个异常时,一定要将异常 A 放在异常 B 之前捕获,如果将异常 B 放在异常 A 之前,那么将永远匹配到异常 B,异常 A 将永远不可能执行,并且编译器将会报错。

2.4 自定义异常

尽管 Java SE 的 API 已经为我们提供了数十种异常类,然而在实际的开发过程中,你仍然可能遇到未知的异常情况。此时,你就需要对异常类进行自定义。

自定义一个异常类非常简单,只需要让它继承 Exception 或其子类就行。在自定义异常类的时候,建议同时提供无参构造方法和带字符串参数的构造方法,后者可以为你在调试时提供更加详细的信息。

package MyTest;
import java.io.*;
public class MyAriException extends ArithmeticException{
	//自定义异常类,该类继承自ArithmeticException
	public MyAriException() {
		
	}
	public MyAriException(String msg) {
		super(msg);
	}
}
package MyTest;//ExceptionTest。java
import java.util.*;
public class ExceptionTest {
	public static void main(String[]args) {
		int []array=new int[5];
		Arrays.fill(array, 5);
		
		for(int i=4;i>-1;i--) {
			if(i==0) {
				throw new MyAriException("There is an exception");
			}
			System.out.println(array[i]/i);
		}
	}
}

2.5 异常堆栈

当异常抛出后,我们可以通过异常堆栈追踪程序的运行轨迹,以便我们更好的DEBUG。

package MyTest;

public class ExceptionStackTrace {
	private static void method1() {
		method2();
	}
	private static void method2() {
		throw new NullPointerException();
	}
	public static void main(String[]args) {
		try {
			method1();
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
}

通过上面的异常堆栈轨迹,在对比我们方法的调用过程,可以得出异常信息中首先打印的是距离抛出异常最近的语句,接着是调用该方法的方法,一直到最开始被调用的方法。从下往上看,就可以得出程序运行的轨迹。

what's the difference betwenn int and Integer?

what's the difference between throw and throws?

class in "public class"?

发布了51 篇原创文章 · 获赞 7 · 访问量 7464

猜你喜欢

转载自blog.csdn.net/Jason6620/article/details/103210669