花几千上万学习Java,真没必要!(二十七)

1、Math类:

package mathtest.com;
public class MathDemo {  
	  
    public static void main(String[] args) {  
        // 定义圆的半径  
        double radius = 5.0;  
          
        // 计算并打印圆的周长  
        double circumference = 2 * Math.PI * radius;  
        System.out.printf("圆的周长: %.2f%n", circumference);  
          
        // 计算并打印圆的面积  
        double area = Math.PI * Math.pow(radius, 2);  
        System.out.printf("圆的面积: %.2f%n", area);  
          
        // 假设要计算以该圆为底面的球体的体积和表面积  
        // 球的半径与圆的半径相同  
          
        // 计算并打印球体的体积  
        double volume = (4.0 / 3) * Math.PI * Math.pow(radius, 3);  
        System.out.printf("球体的体积: %.2f%n", volume);  
          
        // 计算并打印球体的表面积  
        double surfaceArea = 4 * Math.PI * Math.pow(radius, 2);  
        System.out.printf("球体的表面积: %.2f%n", surfaceArea);  
          
        // Math.round()和Math.floor()的使用  
        double number = 123.456;  
        System.out.println("Math.round(number): " + Math.round(number)); // 四舍五入  
        System.out.println("Math.floor(number): " + Math.floor(number)); // 向下取整  
          
        // Math.max()和Math.min()的使用  
        int a = 10, b = 20;  
        System.out.println("Math.max(a, b): " + Math.max(a, b));  
        System.out.println("Math.min(a, b): " + Math.min(a, b));  
          
        // Math.abs()的使用  
        int negativeNumber = -5;  
        System.out.println("Math.abs(negativeNumber): " + Math.abs(negativeNumber));  
          
        // Math.sqrt()和Math.pow()的使用  
        double squareRoot = Math.sqrt(16);  
        System.out.println("Math.sqrt(16): " + squareRoot);  
          
        double power = Math.pow(2, 3); // 2的3次方  
        System.out.println("Math.pow(2, 3): " + power);  
        
  
        double angleRadians = Math.toRadians(45); // 将角度转换为弧度  
 
        // 计算并打印指定角度的正弦、余弦和正切值  
        double sinValue = Math.sin(angleRadians);  
        double cosValue = Math.cos(angleRadians);  
        double tanValue = Math.tan(angleRadians);  
        System.out.printf("sin(%d°) = %.2f%n", (int) Math.toDegrees(angleRadians), sinValue);  
        System.out.printf("cos(%d°) = %.2f%n", (int) Math.toDegrees(angleRadians), cosValue);  
        System.out.printf("tan(%d°) = %.2f%n", (int) Math.toDegrees(angleRadians), tanValue);  
  
        
        // 计算e的x次幂和a的x次幂  
        double expE = Math.exp(1); // e的1次幂,即e本身  
        double expA = Math.pow(2, 3); // 2的3次幂  
        System.out.println("e^1 = " + expE);  
        System.out.println("2^3 = " + expA);  
  
        
        // 计算自然对数和以10为底的对数  
        double logE = Math.log(Math.E);  
        double log10 = Math.log10(100); 
        System.out.println("ln(e) = " + logE);  
        System.out.println("log10(100) = " + log10);  
    }  
}

运行结果如下:

 

2、System类:

package mathtest.com;
import java.util.Arrays;

public class SystemDemo {  
	  
    public static void main(String[] args) {  
        // 使用System.out.println打印欢迎信息  
        System.out.println("欢迎来到System类演示程序!");  
  
        // 设置和获取系统属性  
        // 设置一个自定义的系统属性  
        System.setProperty("my.custom.property", "Hello, World!");  
        // 获取并打印设置的系统属性  
        String customProperty = System.getProperty("my.custom.property");  
        System.out.println("自定义系统属性: " + customProperty);  
  
        // 获取一个不存在的系统属性,并处理NullPointerException(实际上System.getProperty不会抛出此异常,而是返回null)  
        String nonExistentProperty = System.getProperty("non.existent.property");  
        if (nonExistentProperty == null) {  
            System.out.println("指定的系统属性不存在。");  
        }  
  
        // System.currentTimeMillis()  
        long startTime = System.currentTimeMillis();  
        // 耗时操作  
        try {  
            Thread.sleep(2000); // 休眠2秒  
        } catch (InterruptedException e) {  
            e.printStackTrace();  
        }  
        long endTime = System.currentTimeMillis();  
        System.out.println("耗时操作执行了大约 " + (endTime - startTime) + " 毫秒。");  
  
        // System.exit()的使用,用于在程序遇到严重错误时退出  
        //实际应用中,通常会在捕获到严重错误或异常情况时调用System.exit()终止程序。
        try {  
            // 假设有一个条件判断,如果满足则抛出异常  
           // throw new Exception("发生了一个严重的错误,程序将退出。");  
        } catch (Exception e) {  
            e.printStackTrace();  
            System.out.println("由于发生错误,程序将退出。");  
            //System.exit(1); // 非零值通常表示异常退出  
        }  
  
        // 以下代码在上面的System.exit(1)之后不会执行  
        System.out.println("这行代码不会执行,因为程序已经退出了。");  
  
        // Arrays.copyOf和System.arraycopy的使用  
        int[] originalArray = {1, 2, 3, 4, 5};  
        // 使用System.arraycopy复制数组
        int[] copiedArray = new int[originalArray.length];  
        System.arraycopy(originalArray, 0, copiedArray, 0, originalArray.length);  
        // 使用Arrays.copyOf 
        int[] anotherCopiedArray = Arrays.copyOf(originalArray, originalArray.length);  
  
        // 打印复制后的数组
        System.out.println("使用System.arraycopy复制的数组: " + Arrays.toString(copiedArray));  
        System.out.println("使用Arrays.copyOf复制的数组: " + Arrays.toString(anotherCopiedArray));  
        // 如果移除System.exit(1)的调用,那么所有打印语句都将执行。  
    }  
}  

运行结果如下:

 

3、Object类:

测试代码1:

package mathtest.com;
public class ObjectClass {  
    private String data;  
  
    // 构造方法  
    public ObjectClass(String data) {  
        this.data = data;  
    }  
  
    public String getData() {
		return data;
	}

	public void setData(String data) {
		this.data = data;
	}

	// 重写 toString 方法打印类名和哈希码  
    @Override  
    public String toString() {  
        // 使用 Integer.toHexString 将哈希码转换为十六进制字符串 。 
        // 为了保持哈希码的正数表示,可以使用 | 0x00000000FFFFFFFFL 与操作 。 
        // 对大多数用途来说,直接转换通常就足够。  
        return getClass().getName() + "@" + Integer.toHexString(hashCode());  
    }  
  
    public static void main(String[] args) {  
    	ObjectClass obj = new ObjectClass("Hello, World!");  
        //调用 toString() 方法打印对象的类名和哈希码。
    	//哈希码是基于对象的内存地址计算得出的。
    	//当多次运行程序或创建同一个类的多个实例时,哈希码可能会不同。
        System.out.println(obj); 
    }  
}

运行结果如下:

 

测试代码2:

package mathtest.com;
public class Person {  
    private String name;  
    private int age;  
  
    // 构造方法 
    public Person(String name, int age) {  
        this.name = name;  
        this.age = age;  
    }  
  
    public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}

	@Override  
    public String toString() {  
        // 使用StringBuilder构建字符串
		//Person类重写toString()方法,返回一个包含name和age信息的字符串。
        StringBuilder sb = new StringBuilder();  
        sb.append("Person{name='").append(name).append('\'');  
        sb.append(", age=").append(age);  
        sb.append('}');  
        return sb.toString();  
    }  
  
    public static void main(String[] args) {  
        Person person = new Person("Alice", 30);  
        //使用重写后的toString()方法  
        //在控制台打印Person对象,得到一个更有意义的输出,而不是默认的哈希码。
        System.out.println(person); 
    }  
}

 运行结果如下:

 

4、equals方法:

package mathtest.com;
import java.util.HashSet;
//equals方法首先检查obj是否是this的引用(即比较两个引用是否指向同一个对象),
//然后检查obj是否为null或者obj是否属于与this相同的类型。
//它将obj转换为Cup类型(这是安全的,因为已经检查了类型),并比较两个Cup对象的material和volume属性。
//在比较字符串时,使用material == cup.material检查引用是否相同。
//使用material != null && material.equals(cup.material)检查字符串内容是否相同。
//这是处理字符串比较时的常见做法,以避免NullPointerException。
//如果material字段在逻辑上不应该为null,可能还需要添加对null的检查来确保类的健壮性。
public class Cup {  
    private String material; // 杯子材质  
    private int volume; // 杯子容量,以毫升为单位  
  
    // 构造方法  
    public Cup(String material, int volume) {  
        this.material = material;  
        this.volume = volume;  
    }  
  
    public String getMaterial() {
		return material;
	}

	public void setMaterial(String material) {
		this.material = material;
	}

	public int getVolume() {
		return volume;
	}

	public void setVolume(int volume) {
		this.volume = volume;
	}


	// 重写equals方法  
    @Override  
    public boolean equals(Object obj) {  
        // 检查是否为同一个对象的引用  
        if (this == obj) return true;  
        // 检查是否为null或者类型是否相同  
        if (obj == null || getClass() != obj.getClass()) return false;  
        // 转换类型  
        Cup cup = (Cup) obj;  
        // 比较属性值  
        return volume == cup.volume &&  
               (material == cup.material || (material != null && material.equals(cup.material)));  
    }  
  
    // 重写hashCode方法以保持equals和hashCode的一致性  
    @Override  
    public int hashCode() {  
        int result = material != null ? material.hashCode() : 0;  
        result = 31 * result + volume;  
        return result;  
    }  
  
    // 重写toString方法  
    @Override  
    public String toString() {  
        return "Cup{" +  
               "material='" + material + '\'' +  
               ", volume=" + volume +  
               '}';  
    }  
  
    public static void main(String[] args) {  
        Cup cup1 = new Cup("Ceramic", 300);  
        Cup cup2 = new Cup("Ceramic", 300);  
        Cup cup3 = new Cup("Glass", 300);  
  
        // equals方法  
        System.out.println(cup1.equals(cup2)); // 输出 true,因为材质和容量相同  
        System.out.println(cup1.equals(cup3)); // 输出 false,因为材质不同  
        System.out.println(cup1.equals(null)); // 输出 false,因为obj为null  
        // 通常不会直接与Object类型的null进行比较。
  
        // hashCode方法(通过添加到HashSet间接演示)  
        HashSet<Cup> cups = new HashSet<>();  
        cups.add(cup1);  
        System.out.println(cups.contains(cup2)); // 输出 true,因为hashCode和equals都表明cup1和cup2相等  
        // toString方法  
        System.out.println(cup1); // 输出 Cup{material='Ceramic', volume=300}  
    }  
}

运行结果如下:

 

 

 

 

  • 24
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值