JAVA入门学习(十一)—— Math类、Date类、异常(包括自定义异常)

一、Math类

  1. 被final修饰

public final class Math
不能有子类

2.基本方法:

public static  void test(){
		 
		// Math.sqrt()计算平方根
		System.out.println(("Math.sqrt(16)----:"+Math.sqrt(16)));//4.0
		//Math.cbrt()计算立方根
		System.out.println(("Math.cbrt(8)----:"+Math.cbrt(8)));//2.0
		//Math.hypot(x,y)计算 (x的平方+y的平方)的平方根 
		System.out.println(("Math.hypot(3,4)----:"+Math.hypot(3,4)));//5.0
		 
		System.out.println(("------------------------------------------"));
		// Math.pow(a,b)计算a的b次方
		System.out.println(("Math.pow(3,2)----:"+Math.pow(3,2)));//9.0
		// Math.exp(x)计算e^x的值
		System.out.println(("Math.exp(3)----:"+Math.exp(3)));//20.085536923187668
		 
		System.out.println(("------------------------------------------"));
		//Math.max();计算最大值
		System.out.println(("Math.max(2.3,4.5)----:"+Math.max(7,15)));//15
		//Math.min();计算最小值 
		System.out.println(("Math.min(2.3,4.5)----:"+Math.min(2.3,4.5)));//2.3
		 
		//Math.abs求绝对值 
		System.out.println(("------------------------------------------"));
		System.out.println(("Math.abs(-10.4)----:"+Math.abs(-10.4)));//10.4
		System.out.println(("Math.abs(10.1)----:"+Math.abs(10.1)));//10.1
		 
		//Math.ceil天花板的意思,大于这个数的最小的那个整数。
		System.out.println(("------------------------------------------"));
		System.out.println(("Math.ceil(-10.1)----:"+Math.ceil(-10.1)));//-10.0
		System.out.println(("Math.ceil(10.7)----:"+Math.ceil(10.7)));//11.0
		System.out.println(("Math.ceil(-0.7)----:"+Math.ceil(-0.7)));//-0.0
		System.out.println(("Math.ceil(0.0)----:"+Math.ceil(0.0)));//0.0
		System.out.println(("Math.ceil(-0.0)----:"+Math.ceil(-0.0)));//-0.0
		System.out.println(("Math.ceil(-1.7)----:"+Math.ceil(-1.7)));//-1.0
		 
		//Math.floor地板的意思,小于这个数的最大的那个整数。
		System.out.println(("------------------------------------------"));
		System.out.println(("Math.floor(-10.1)----:"+Math.floor(-10.1)));//-11.0
		System.out.println(("Math.floor(10.7)----:"+Math.floor(10.7)));//10.0
		System.out.println(("Math.floor(-0.7)----:"+Math.floor(-0.7)));//-1.0
		System.out.println(("Math.floor(0.0)----:"+Math.floor(0.0)));//0.0
		System.out.println(("Math.floor(-0.0)----:"+Math.floor(-0.0)));//-0.0
		 
		 
		 
		//Math.random 取得一个大于或者等于0.0小于不等于1.0的随机数[0,1)
		System.out.println(("------------------------------------------"));
		System.out.println(("Math.random()----:"+Math.random()));//输出[0,1)间的随机数 0.8979626325354049
		System.out.println(("Math.random()*100----:"+Math.random()*100));//输出[0,100)间的随机数 32.783762836248144
		/**
		  * Random类
		  *Random random = new Random();
		  *int i = random.nextInt(10);//[0,10) 
		*/
		 
		
		// Math.rint 返回最接近参数的
		// 方法返回最接近参数的整数值。若存在两个这样的数,则返回其中的偶数值。  
		//  即   Math.rint(10.5) 最接近的为10.0和11.0,返回偶数值10.0
		System.out.println(("------------------------------------------"));
		System.out.println(("Math.rint(10.1)----:"+Math.rint(10.1)));//10.0
		System.out.println(("Math.rint(10.7)----:"+Math.rint(10.7)));//11.0
		System.out.println(("Math.rint(-10.5)----:"+Math.rint(-10.5)));//-10.0
		System.out.println(("Math.rint(-10.51)----:"+Math.rint(-10.51)));//-11.0
		System.out.println(("Math.rint(-11.5)----:"+Math.rint(-11.5))); //-12.0
		System.out.println(("Math.rint(11.5)----:"+Math.rint(11.5))); //12
		System.out.println(("Math.rint(-10.2)----:"+Math.rint(-10.2)));//-10.0
		System.out.println(("Math.rint(9)----:"+Math.rint(9)));//9.0
		
		/**
		 * round 表示"四舍五入",算法为Math.floor(x+0.5) ,即将原来的数字加上 0.5 后再向下取整,
		 * 所以 Math.round(11.5) 的结果为 12,Math.round(-11.5) 的结果为 -11,Math.round(-11.51)的结果为 -12
		 */
		//Math.round 四舍五入 float时返回int值,double时返回int值 
		System.out.println(("------------------------------------------"));
		System.out.println(("Math.round(10.1)----:"+Math.round(10.1)));//10
		System.out.println(("Math.round(10.7)----:"+Math.round(10.7)));//11
		System.out.println(("Math.round(-10.5)----:"+Math.round(-10.5)));//-10
		System.out.println(("Math.round(-10.51)----:"+Math.round(-10.51)));//-11
		System.out.println(("Math.round(-11.5)----:"+Math.round(-11.5))); //-11
		System.out.println(("Math.round(11.51)----:"+Math.round(11.51)));  //12
		System.out.println(("Math.round(-10.2)----:"+Math.round(-10.2)));//-10
		System.out.println(("Math.round(9)----:"+Math.round(9)));//9
		 		 
		//Math.nextUp(a) 返回比a大一点点的浮点数
		System.out.println(("------------------------------------------"));
		System.out.println(("Math.nextUp(1.2)----:"+Math.nextUp(1.2)));//1.2000000000000002
		 		 
		//Math.nextDown(a) 返回比a小一点点的浮点数
		System.out.println(("------------------------------------------"));
		System.out.println(("Math.nextDown(1.2)----:"+Math.nextDown(1.2)));//1.1999999999999997
		 		 
		//Math.nextAfter(a,b) 返回(a,b)或(b,a)间与a相邻的浮点数 b可以比a小	 
		System.out.println(("------------------------------------------"));
		System.out.println(("Math.nextAfter(1.2, 2.7)----:"+Math.nextAfter(1.2, 2.7)));//1.2000000000000002
		System.out.println(("Math.nextAfter(1.2, -1)----:"+Math.nextAfter(1.2, -1)));//1.1999999999999997
		 
		}

🔺小练习:随机数int,猜数游戏

public static void test(){
		Random random = new Random();
		int i = random.nextInt(10) + 1;
		System.out.println(i);
		while(true) {
			System.out.println("请输入一个1-10随机数:");
			Scanner sc = new Scanner(System.in);
			int a = sc.nextInt();
			if(a == i) {
				System.out.println("猜数正确!");
				break;
			}
			else {
				System.out.println("猜数错误!");
			}
		}
	}

二、Date类

基本方法:

Date对象方法:
首先得先创建一个时间对象 new Date()

get系列:
getDate() 返回一个月中的某一天(1-31)
getDay()    返回一周中的某一天(0-6)
getFullYear()  返回四位数的年份
getMonth()   返回月份(0-11 0是一月)
getHours()   返回的是当前的小时(0-23)
getMinutes()  返回的是当前的分钟(0-59)
getSeconds()  返回的是当前的秒(0-59)
getTime()    返回的是197011日至今的毫秒数
----------------------------------------------------
set系列:
parse()    返回197011日到指定日期的毫秒数
setDate()   设置一月的某一天(1-31)
setFullYear()  设置年份
setMonth()   设置月份(0-11)
setHours()    设置小时(0-23)
setMinutes()   设置分钟(0-59)
setSeconds()  设置秒数(0-59)
setTime      以毫秒数设置Date

SimpleDateFormat类日期的表示方式:
在这里插入图片描述
常用格式:
在这里插入图片描述
🔺小练习:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Calendar;
import java.util.Date;

public class Test5 {

	//日期格式与字符串的转换
	public static void test1() throws ParseException {
		System.out.println(new Date()); //Sun Aug 02 14:27:21 GMT+08:00 2020
		//将日期转换成字符串格式输出
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
		System.out.println(sdf.format(new Date()));  //2020.08.02 14:27:21
		
		//将字符串类型转换成Date类型输出
		String str = "2020.08.02 14:24:27";
		System.out.println(sdf.parse(str));  //Sun Aug 02 14:24:27 GMT+08:00 2020
	}
	
	//使用Calendar类
	public static void test2() {
		//获取对象
		Calendar c = Calendar.getInstance();
		System.out.println(c);
		System.out.println(c.get(Calendar.YEAR)
				+ "-" + (c.get(Calendar.MONTH) + 1)
				+ "-" + c.get(Calendar.DATE));
	}
	
	//jdk8新增的时间日期类
	public static void test3() {
		LocalDate d = LocalDate.now();
		LocalTime t = LocalTime.now();
		LocalDateTime dt = LocalDateTime.now();
		System.out.println(d);  //2020-08-02
		System.out.println(t);   //14:34:03.618
		System.out.println(dt);   //2020-08-02T14:34:03.618
	}
	
	public static void main(String[] args) throws ParseException {
		test3();
	}
}

三、异常

1.定义:

异常就是有异于常态,和正常情况不一样,有错误出现。在java中,阻止当前方法或作用域的情况,称之为异常。

2.分类:

在这里插入图片描述

继承关系  
Throwable
  Error:不能处理的 XXXError
  Exception:能处理的   xxxException
    RuntimeException :运行时异常
        NullPointerException,ArrayIndexOfBoundsException
        StringIndexOfBoundsException,ArithmeticException等
    编译时产生的异常:
		IOException,FileNotFoundException,
        InterruptedException,SQLException 等

运行时异常不强制处理,如果代码写的严谨,可以避免运行时异常的产生。编译时产生的异常必须处理

3.异常处理的两种方式:

1.throws 抛出异常(声明异常) --》在方法上
2.try-catch块捕获异常  --》在方法体里面的代码上
   异常代码块:在日志文件中保存堆栈信息
             外行,翻译异常信息
             检查代码:直接打印堆栈信息

4.异常块的正确使用语法

> try-catch    
> try-catch-finally    
> try-catch-catch...finally   
> try-finally:语法是正确的,但不能捕获异常
> try-catch可以嵌套使用try-catch> 即: try { 			
>        try {}catch(Exception e){}finally{} 		
>     }catch(Exception e){}finally{}

注意:
try?catch?finally,try里有return,finally还执行么

答:肯定会执行。

finally{}块的代码。 只有在try{}块中包含遇到System.exit(0)。 之类的导致Java虚拟机直接退出的语句才会不执行。

当程序执行try{}遇到return时,程序会先执行return语句,但并不会立即返回——也就是把return语句要做的一切事情都准备好,也就是在将要返回、但并未返回的时候,程序把执行流程转去执行finally块,当finally块执行完成后就直接返回刚才return语句已经准备好的结果。

5.执行过程:

如果try中有异常,从异常语句开始不再执行后边的语句
跳到catch执行
不管有无异常,finally块都会执行

public class Test6 {

	public static int test6() {
		try {
			return 1;
		} catch (Exception e) {
			return 2;
		} finally {
			System.out.print("end");
		}
	}
	
	public static int test6_1() {
		int i = 0;
		try {
			return i++;
		} catch (Exception e) {
			return 2;
		} finally {
			i++;
			System.out.print(i);
			System.out.print("end");
		}
	}

	public static int test6_2() {
		int i = 0;
		try {
			return i++;
		} catch (Exception e) {
			return 2;
		} finally {
			i++;
			System.out.print("end");
			//会屏蔽掉tru里面的return
			return i;
		}
	}

	// 在 finally块中,尽量不要写return,有时候会屏蔽异常代码
	public static String test7(String name) {
		try {
			name.length();
		} finally {
			return name + "hello";
		}
	}

	public static void main(String[] args) {
		System.out.println(test6());  // end 1
		System.out.println(test6_1());   // 2 end 0
		System.out.println(test6_2());  //end 2
		System.out.println(test7("tao")); //taohello
	}

}

6.自定义异常类:继承现有的异常类

直接上代码练习:

public interface Message {

	//AgeException
	String message = "请输入正确的年龄范围(1-100)";
}

---------------------------------------------------------
public class AgeException extends Exception {

	public AgeException() {
		super(Message.message);
	}
}

------------------------------------------------------------

import java.util.Scanner;

/**
 * 使用自定义的异常
 * @author 陶沅玱
 *
 */
public class Test07 {

	//判断输入的年龄是否合理
	//抛出异常throws 在方法上,交给jvm处理
	public static void test() throws AgeException {
		Scanner sc = new Scanner(System.in);
		System.out.println("输入您的年龄:");
		int a = sc.nextInt();
		
		if(a<0 || a>100 ) {
			throw new AgeException();
		}
		else {
			System.out.println("年龄合理!");
		}
	}
	
	//抛出异常 try-catch块
	public static void main(String[] args)  {
		try {
			test();
		} catch (AgeException e) {
			// TODO Auto-generated catch block
			System.out.println(Message.message);
		}
	}
}

运行结果:
输入您的年龄:
20
年龄合理!
---------------
输入您的年龄:
999
请输入正确的年龄范围(1-100

7.带有异常的方法的重写规则:(指编译时异常,和运行时异常无关)

子类异常<=父类的

class A{
	//编译时异常
	public void test()throws IOException,SQLException{	
	}
	public void test2(){		
	}
	public void test3(){		
	}
}
public class Demo4 extends A {
	public void test()throws IOException{		
	}
	//子类多出运行时异常不会报错
    public void test2()throws RuntimeException{		
	}
	//报错
	//public void test3()throws Exception{	
	//}
}

8.throw 和 throws的区别

throw :抛出异常                    throws:声明异常
        在方法内                            方法声明
      + 异常类的对象                      + 异常类的类型
      只能有一个异常类的对象               多个异常类型,用,隔开

🔺异常小结

小结:
1.异常的继承关系
2.Exception
3.处理异常
4.try-catch多种格式
5.自定义异常
   extends Exception
   		super(异常信息);
   用:if(){throw 异常类对象}
6.方法重写的异常(编译时异常)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值