Math 類
math.直接調用
public static void main(String[] args) { System.out.println(Math.E); System.out.println(Math.ceil(2.1)); // 上天花板數 System.out.println(Math.floor(2.9)); // 下天花板數 System.out.println(Math.abs(3.5)); //絕對值 System.out.println(Math.round(3.5)); //四舍五入 System.out.println(Math.random()); //0.0~1.0的隨機數、 System.out.println(Math.pow(2, 3)); //返回2的3次方 System.out.println(Math.sqrt(81)); //開平方 }
calendar類:
public static void main(String[] args) { //受保護的構造方法的獲得實例的方式 Calendar ca = Calendar.getInstance(); //日歷返日期 Date date = ca.getTime(); System.out.println(date); //獲取時間 System.out.println(ca.get(ca.YEAR)); System.out.println(ca.get(ca.MONTH)+1); }
simpledateformat:日期格式化
public static void main(String[] args) { //日期格式化 a 代表的是上午 Date date = new Date(); SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss a" ); String format = sf.format(date); System.out.println(format); }
comparable接口
實現這個接口
class Dog implements Comparable<Dog>{ int age; String name; public Dog(int age, String name) { super(); this.age = age; this.name = name; } @Override public int compareTo(Dog o) { //比較信息 if(this.age > o.age){ return 1; }else{ return -1; } } } public class CompareTest { public static void main(String[] args) { Dog dog1 = new Dog(2, "小胡"); Dog dog2 = new Dog(3, "胖胖"); System.out.println(dog1.compareTo(dog2)); } }
package com.qc.java1801.api; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.TreeSet; class Student{ String name; int score; public Student(String name, int score) { super(); this.name = name; this.score = score; } @Override public String toString() { return "Student [name=" + name + ", score=" + score + "]"; } } /*class compar implements Comparator<Student>{ @Override public int compare(Student o1, Student o2) { return o1.score - o2.score; } }*/ public class ComparetoTest { public static void main(String[] args) { List<Student> students = new ArrayList<Student>(); students.add(new Student("張三", 90)); students.add(new Student("李四", 80)); students.add(new Student("王二麻", 100)); //用了匿名內部類 Collections.sort(students, new Comparator<Student>() { @Override public int compare(Student o1, Student o2) { return o1.score - o2.score; } }); System.out.println(students); } }
comparator 和 comparable區別;
comparable自己實現
comparator需要第三方實現
抓取異常和拋異常
public static void main(String[] args) { Park.ticket = 10000; Scanner sc = new Scanner(System.in); System.out.println("請輸入年齡"); try { int age = sc.nextInt(); System.out.println(Park.sellticket(age)); } catch (InputMismatchException e) { System.out.println("輸入的格式不正確"); } catch (Exception e) { System.out.println(e.getMessage()); } } static class Park{ static int ticket; public static int sellticket(int age) throws Exception{ if(age > 100 || age < 0){ throw new Exception("年齡不合適"); }else if(age > 60){ ticket = 0; }else if(age < 10){ ticket = ticket/2; }else{ return ticket; } return ticket; } }