zoukankan      html  css  js  c++  java
  • Java中常用方法(Number&Math)

    Java中常用方法(Number&Math)

    包装类

    在实际开发过程中,我们经常会遇到需要使用对象,而不是内置数据类型的情形。为了解决这个问题,Java 语言为每一个内置数据类型提供了对应的包装类。

    基本数据类型 byte short int long float double char boolean
    包装类 Byte Short Integer Long Float Double Character Boolean

    装箱和拆箱

    装箱:自动将基本数据类型转换成包装器类型。

    Integer a = 128;  // 装箱,相当于 Integer.valueOf(128);
    

    拆箱:自动将包装器类型转换为基本数据类型。

    int t = a; //拆箱,相当于 a.intValue() 
    

    方法

    ​ toString() :将数字以字符串形式返回

    String s1 = Byte.toString((byte)1);
    

    ​ XXXValue() : 将包装类转换成基本类型数据

    Byte b1 = 1;  
    byte b2 = b1.byteValue(); //拆箱
    

    ​ ValueOf() : 将基本类型数据转换成包装类

    Integer intvalue = Integer.valueOf(123);
    

    ​ parseXXX() : 包装类的静态方法 - 字符串转数字(Character除外)

    int a = Integer.parseInt("111");
    boolean b = Boolean.parseBoolean("true");
    

    Number类

    floor直接取其含义,也就是“地板”,地板在脚下,即向下取整

    ceil****是ceiling的缩写,也就是“天花板”,天花板在头顶上,即向上取整**。

    round()的四舍五入取整。将传入的数字加上0.5后再向下取整

    double d = 100.675;
    float f = -90;
    
    System.out.println(Math.floor(d));	//100.0
    System.out.println(Math.floor(f));	//-90.0
    
    System.out.println(Math.ceil(d));	//101.0
    System.out.println(Math.ceil(f));	//-90.0
    
    System.out.println(Math.round(d));	//101.0
    

    Random类

    此类的实例用于生成为随机数。

    可以传入参数设置种子数,相同种子数的Random对象,相同次数生成的随机数字是完全相同的。

    Random random = new Random();
    random.setSeed(50); //设置种子数
    for (int i = 0; i < 10; i++) {
        System.out.print(random.nextInt(10) + "-");
    }
    Random  random2 = new Random(50); //设置相同种子数
    for (int i = 0; i < 10; i++) {
        System.out.print(random2.nextInt(10) + "-");
    }
    

    相同种子数的实例对象产生的随机值是完全一样的

    String类

    length():字符串长度

    equals():比较内容

    equalsIgnoreCase():忽略大小写比较内容

    toLowerCase():转换为小写

    toUpperCase():转换为答谢

    concat():拼接字符串

    indexOf():查找第一个出现的位置

    lastIndexOf():查找最后一个出现的位置

    subString():截取字符串,包前不包后

    trim():去除前后的空格

    startsWith():判断是否已某个字符串开头

    endsWith():判断是否已某个字符串结尾

    split():分割字符串为String数组

    replace():替换字符串

    replaceAll():可以支持正则表达式替换字符串

  • 相关阅读:
    matplotlib 进阶之origin and extent in imshow
    Momentum and NAG
    matplotlib 进阶之Tight Layout guide
    matplotlib 进阶之Constrained Layout Guide
    matplotlib 进阶之Customizing Figure Layouts Using GridSpec and Other Functions
    matplotlb 进阶之Styling with cycler
    matplotlib 进阶之Legend guide
    Django Admin Cookbook-10如何启用对计算字段的过滤
    Django Admin Cookbook-9如何启用对计算字段的排序
    Django Admin Cookbook-8如何在Django admin中优化查询
  • 原文地址:https://www.cnblogs.com/MonkeySun/p/13275934.html
Copyright © 2011-2022 走看看