Java笔记(6)-Math、BIgInteger、DecimalFormat、Pattern和Macth、Scanner、System.exit()



  我是天空里的一片云,
  偶尔投影在你的波心——
    你不必讶异,
    更无须欢喜——
  在转瞬间消灭了踪影。
  你我相逢在黑夜的海上,
  你有你的,我有我的,方向;
    你记得也好,
    最好你忘掉,
  在这交会时互放的光亮。
  
   —–徐志摩《偶然》

  

Math类

字段

java.lang.Math类的字段:

static double E -- 这就是double值,该值是比任何其他更近到e,自然对数的基础上. 2.718281828459045

static double PI -- 这就是双值,该值是比任何其他更接近到pi,一个圆的圆周比其直径. 3.141592653589793

类方法

  • static double abs(double a) 此方法返回一个double值的绝对值.

  • static double ceil(double a) 此方法返回最小的(最接近负无穷大)double值,大于或等于参数,并等于一个整数.

  • static double cos(double a) 此方法返回一个角的三角余弦.

  • static float max(float a, float b) 此方法返回的两个浮点值最大的那一个.

  • static float min(float a, float b) 此方法返回的两个较小的浮动值.

  • static double pow(double a, double b) 此方法返回的第一个参数的值提升到第二个参数的幂

  • static double random() 该方法返回一个无符号的double值,大于或等于0.0且小于1.0.

更多方法

BigInteger类

处理大整数,java.math包中的BigInteger类提供任意精度的整数运算。

BIginteger方法

  • BigInteger abs() 返回其值是此 BigInteger 的绝对值的 BigInteger。

  • BigInteger add(BigInteger val) 返回其值为 (this + val) 的 BigInteger。

  • BigInteger multiply(BigInteger val) 返回其值为 (this * val) 的 BigInteger。

    更多方法

示例

import java.math.BigInteger;

public class Main {
    public static void main(String[] args) {
        double a = 5.0;
        double st = Math.sqrt(a);
        System.out.println(a + "平方根:" + st);
        BigInteger result = new BigInteger("0");
        BigInteger one = new BigInteger("123456789");
        BigInteger two = new BigInteger("987654321");
        result = one.add(two);
        System.out.println("和:" + result);
        result = one.multiply(two);
        System.out.println("积:" + result);
    }
}
5.0平方根:2.23606797749979:1111111110:121932631112635269

DecimalFormat类

对数字进行格式化

import java.text.DecimalFormat;

public class Main {
    public static void main(String[] args) {
        // DecimalFormat的构造方法 ,格式化整数位和小数位
        DecimalFormat format1 = new DecimalFormat("00000.000");
        /**
         * 00000.000 只能有一个"." .前的0保留最少整数位 .后的0保留最多整数位
         */
        String result = format1.format(1545.2323);
        System.out.println("" + result);// 01545.232

        /**
         * 如果分组中有多个分隔符,则最后一个分隔符和整数结尾之间的间隔才是分组的大小
         * "#,##,###,###00.00","#######,####00.00","##,####,###00.00"都是等同的,分组的大小是6
         */
        DecimalFormat format2 = new DecimalFormat("####,###00.00");
        String result2 = format2.format(123456789.9876543);
        System.out.println("" + result2);// 1234,56789.99

        /**
         * 格式化成百分数和千分数
         */
        DecimalFormat format3 = new DecimalFormat("###.00");
        String result3 = format3.format(123456789.9876543);
        System.out.println("" + result3);// 123456789.99

        format3 = new DecimalFormat("###.00%");
        result3 = format3.format(123456789.9876543);
        System.out.println("" + result3);// 12345678998.77%

        format3 = new DecimalFormat("###.00\u2030");
        result3 = format3.format(123456789.9876543);
        System.out.println("" + result3);// 123456789987.65‰
        /**
         * 格式化为科学计数加 E0
         * 格式化为货币值加 $ ¥
         */
    }
}
01545.232
1234,56789.99
123456789.99
12345678998.77%
123456789987.65

将格式化的字符串转换为数字

    /**
     * df.parse(money)返回的是一个Number对象
     * Number对象调用doubleValue()返回对象中含有的数字
     */
    String money = "9,545,555.362¥";
    DecimalFormat df = new DecimalFormat("#,##,##0.000");
    try {
        Number num = df.parse(money);
        System.out.println(""+num.doubleValue());
    } catch (ParseException e) {}

Pattern类和Macth类

模式匹配就是检索和指定模式匹配的字符串。Java提供了专门用来进行模式匹配的Patternhe Match类,这些类在java.util.regex包中。

模式对象

使用Pattern类创建一个对象,称作模式对象,模式对象是对正则表达式的封装。

static Pattern compile(String regex)

static Pattern compile(String regex,int flags)

flages

Pattern.CASE_INSENSITIVE
Pattern.MULTILINE
Pattern.DOTALL
Pattern.UNICODE_CASE
Pattern. CANON_EQ 忽略大小写

匹配对象

模式对象p调用matcher(CharSequence input)方法放回一个Matcher对象m,称作匹配对象,参数input可以是任何一个实现了CharSequence接口的类创建的对象,String类 和StringBuffer类都实现了CharSequence接口。

  • public boolean find()
    find会在整个输入中寻找是否有匹配的子字符串,一般我们使用find的流程:

    while(matcher.find()){  
       //在匹配的区域,使用group,replace等进行查看和替换操作  
    }  
  • public boolean matches()
    尝试将整个区域与模式匹配。这个要求整个输入字符串都要和正则表达式匹配。

  • public boolean find(int start)
    从输入字符串指定的start位置开始查找。

  • public boolean lookingAt()
    基本上是matches更松约束的一个方法,尝试将从区域开头开始的输入序列与该模式匹配

更多方法

示例

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        Pattern p;//模式对象
        Matcher m;//匹配对象
        String regex = "(http://|www)\56?\\w+\56{1}\\w+\56{1}\\p{Alpha}+";
        p = Pattern.compile(regex);//初始化模式对象
        String s = "清华大学网址:www.tsinghua.edu.cn,邮电出版社的网址:http://www.ptpress.com";
        m = p.matcher(s);//用待匹配的字符序列初始化匹配对象
        while(m.find()){
            String str = m.group();
            System.out.println(str);
        }
        System.out.println("剔除字符串中的网站地址后得到的字符串:");
        String result = m.replaceAll("");
        System.out.println(result);
    }
}
www.tsinghua.edu.cn
http://www.ptpress.com
剔除字符串中的网站地址后得到的字符串:
清华大学网址:,邮电出版社的网址:

Scanner类

扫描控制台输入

当通过new Scanner(System.in)创建一个Scanner,控制台会一直等待输入,直到敲回车键结束,把所输入的内容传给Scanner,作为扫描对象。如果要获取输入的内容,则只需要调用Scanner的nextLine()方法即可。

Scanner方法

  • delimiter()   返回此 Scanner 当前正在用于匹配分隔符的 Pattern。
  • hasNext()  判断扫描器中当前扫描位置后是否还存在下一段。
  • hasNextLine()   如果在此扫描器的输入中存在另一行,则返回 true。
  • next()  查找并返回来自此扫描器的下一个完整标记。
  • nextLine()  此扫描器执行当前行,并返回跳过的输入信息。

更多方法

next() 方法才将其后输入的空格键、Tab键或Enter键等视为分隔符或结束符
nextLine() 方法的结束符只是Enter键

public class Test {
    public static void main(String[] args) {
        String s1, s2;
        Scanner sc = new Scanner(System.in);
        System.out.print("请输入第一个字符串:");
        s1 = sc.nextLine();
        System.out.print("请输入第二个字符串:");
        s2 = sc.next();
        System.out.println("输入的字符串是:" + s1 + s2);
    }

}
请输入第一个字符串: home  h
请输入第二个字符串:tone  t
输入的字符串是: home  htone //next()方法 t没有记录

示例

import java.util.Calendar;
import java.util.InputMismatchException;
import java.util.Scanner;

public class Input {
    public static void main(String[] args) {
        int year = 0;
        int month = 0;
        int day = 0;
        int year2 = 0;
        int month2 = 0;
        int day2 = 0;
        int sumday = 0;

        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入第一个时间年月日:(依次输入年月日,空格间隔输入)");
        Calendar calendar = Calendar.getInstance();
        try {
            // 输入时间
            year = scanner.nextInt();
            month = scanner.nextInt();
            day = scanner.nextInt();
            // 判断日期格式
            month = checkmonth(month, scanner);
            sumday = getsumday(year, month);
            day = checkday(day, sumday, scanner);
            calendar.set(year, month, day);
            long time1 = calendar.getTimeInMillis();
            System.out.println("您输入的第一年是:" + year + " 年:" + month + " 月:" + day + "日");

            System.out.println("请输入第一个时间的年月日:(依次输入年月日,空格间隔输入)");
            year2 = scanner.nextInt();
            month2 = scanner.nextInt();
            day2 = scanner.nextInt();
            month2 = checkmonth(month2, scanner);
            sumday = getsumday(year2, month2);
            day2 = checkday(day2, sumday, scanner);
            calendar.set(year2, month2, day2);
            long time2 = calendar.getTimeInMillis();
            System.out.println("您输入的第二年是:" + year + " 年:" + month + " 月:" + day + "日");
            System.out.println("相隔天数" + (time2 - time1) / (1000 * 60 * 60 * 24) + "天");

        } catch (InputMismatchException e) {
            System.out.println("请输入合适范围的整数:");
        }
    }

    private static int getsumday(int year, int month) {

        int sumday = 0;
        if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
            sumday = 31;
        }
        if (month == 4 || month == 6 || month == 9 || month == 11) {
            sumday = 30;
        }
        if (month == 2) {
            if ((year % 4 == 0) || (year % 100 != 0) || (year % 400 == 0)) {
                sumday = 29;
            } else {
                sumday = 28;
            }
        }
        return sumday;
    }

    private static int checkmonth(int month, Scanner scanner) {
        while (month < 0 || month > 13) {
            System.out.println("月份输入错误,请重新输入1-12区间");
            month = scanner.nextInt();
        }
        return month;
    }

    private static int checkday(int day, int sumday, Scanner scanner) {
        while (day < 0 || day > sumday) {
            System.out.println("日期输入错误,请重新输入");
            System.out.println("这个月只有" + sumday + "天");
            day = scanner.nextInt();
        }
        return day;
    }
}
请输入第一个时间年月日:(依次输入年月日,空格间隔输入)
2014 10 1
您输入的第一年是:2014 年:10 月:1日
请输入第一个时间的年月日:(依次输入年月日,空格间隔输入)
2015 10 1
您输入的第二年是:2014 年:10 月:1日
相隔天数365天

使用默认分隔标记解析字符串

之前可以用String类的split(String regex)来分解字符串,StringTokenizer类解析字符串中的单词。

默认scanner将空白作为分隔标记,调用next()方法依次返回字符串中的单词
最后的一个单词被返回,hasnext()将返回false,否则为true
nextInt()或nextDouble()可以替代next()将数字型单词转换为int型或double型,类型不对将会报InputMisMatchException异常,这时用next()处理非数字化单词

import java.util.InputMismatchException;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        String cost = "TV cost 876 dollar.Computer cost 2398 dollar.telephone cost 1278 dollar";
        Scanner scanner = new Scanner(cost);
        double sum = 0;

        /**
         * 默认scanner将空白作为分隔标记,调用next()方法依次返回字符串中的单词
         * 最后的一个单词被返回,hasnext()将返回false,否则为true
         * nextInt()或nextDouble()可以替代next()将数字型单词转换为int型或double型,类型不对将会
         * 报InputMisMatchException异常,这时用next()处理非数字化单词
         */
        while(scanner.hasNext()){
            try {
                double price = scanner.nextDouble();
                sum = sum +price;
                System.out.println(price);
            } catch (InputMismatchException e) {
                String t =scanner.next();
            }   
        }
        System.out.println("总消费:"+sum+"元");
    }
}
876.0
2398.0
1278.0
总消费:4552.0

使用正则表达式解析字符串

将正则表达式作为分隔标记

useDelimiter(正则表达式);  和正则表达式匹配的都是分隔标记
import java.util.InputMismatchException;
import java.util.Scanner;

public class Main2 {
    public static void main(String[] args) {
        String cost = "话费清单:市话费32.32元,长途话费23.3元,短信费18元";
        String regex = "[^0123456789.]+";
        Scanner scanner = new Scanner(cost);
        scanner.useDelimiter(regex);
        double sum = 0;
        while(scanner.hasNext()){
            try {
                double price = scanner.nextDouble();
                sum = sum +price;
                System.out.println(price);
            } catch (InputMismatchException e) {
                String t =scanner.next();
            }   
        }
        System.out.println("总通信费用:"+sum+"元");
    }
}
32.32
23.3
18.0
总通信费用:73.62

System类-exit()

System.exit(int status), status可以为0或非0数字,0表示正常关闭虚拟机,关闭应用程序,将使应用程序立即结束执行。
用户从键盘输入的整数之和,如果和超过8000,就关闭虚拟机。

import java.util.Scanner;

public class Exit {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int sum = 0;
        System.out.println("输入一个整数");
        while (scanner.hasNextInt()) {
            int item = scanner.nextInt();
            sum = sum + item;
            System.out.println("目前和:" + sum);
            if (sum >= 8000)
                System.exit(0);// 0表示正常关闭虚拟机
            System.out.println("输入一个整数(输入非整数结束输入)");

        }
        System.out.println("总和:" + sum);
    }
}
输入一个整数
234
目前和:234
输入一个整数(输入非整数结束输入)
2342
目前和:2576
输入一个整数(输入非整数结束输入)
23455
目前和:26031
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值