zoukankan      html  css  js  c++  java
  • day18(上)_System,Runtime,Date,Calendar,Math


    1.System类

    /*
    System:描述系统一些信息
    out:标准输出,默认是控制台
    in:标准输入,默认是键盘.
    
    获取系统属性信息:Properties getProperties()
    Properties:
        Properties 类表示了一个持久的属性集,其上未定义泛型
        Properties 可保存在流中或从流中加载。
        属性列表中每个键及其对应值都是一个字符串。 
    
    因为Properties是Hashtable<Object,Object>的子类,也就是Map集合的一个子类.
    那么可以通过Map中的方法取出集合中的元素.(但是不建议使用继承HashTable允许添加任意对象,可以使用getProperty/setProperty)
    */
    package system;
    import java.util.Properties;
    import java.util.Map;
    import static java.lang.System.out;
    class SystemDemo
    {
        public static void main(String[] args) 
        {
            Properties prop = System.getProperties();
            
            
             //2.如何在系统中自定义一些特有信息?
             /*
             public static String setProperty(String key,String value)
              设置指定键指示的系统属性,返回系统属性以前的值,如果没有以前的值,则返回 null。 
             */
            System.out.println(System.setProperty("userKey","userValue"));
    //null
    //userKey不存在,该键-值添加到了系统属性中
    
    
    
            //1.JVM启动时加载的一些默认信息
            //也可以通过Properties中的Set<String> stringPropertyNames()方法 
            //获取所有属性信息
            
            for(Map.Entry<Object,Object> me : prop.entrySet())//注意继承Hashtable<Object,Object>,因此关系的泛型也确定,
                                                              //Map.Entry<Object,Object>,这里可以不使用泛型,但实际类型参数为Object
            out.println(me.getKey()+"::"+me.getValue());
            
            for(String str : prop.stringPropertyNames())
             out.println(str+”...”);//返回Key值
    
            
            //3.获取指定属性信息
             System.out.println(System.getProperty("os.name"));//Windows 7
           
        
            
            //4.在JVM启动时动态加载一些属性信息(再启动虚拟机的同时,加上一些参数)
             // java -D<name>=<value> 设置系统属性
             System.out.println(System.getProperty("add"));
    //嘿咻
     //利用java -Dadd=嘿咻 动态添加->获取到嘿咻
        }
    }

    系统属性集:

    遍历Properties集合

    for(String str : prop.stringPropertyNames())
             out.println(str);

    stringPropertiesNames

    2.Runtime类:

    /*
    (API)
    Runtime:
    每个 Java 应用程序都有一个 Runtime 类实例,
    使应用程序能够与其运行的环境(所在的系统环境)相连接。
    (因为Java程序是跨平台的) 
    (使java程序在某一个OS下出现一个进程并进行封装->通过Runtime)
    
    
    注意该类没有对外暴露构造方法,说明不可以创建对象
    ->会认为该类中的方法为静态的
    ->但是有非静态方法,说明会提供一个静态方法获取本类对象
    
      private static Runtime currentRuntime = new Runtime();
       public static Runtime getRuntime() {
            return currentRuntime;
        }
      //由以上看出Runtime中运用了单例设计模式:保证每次运行时内存中对象的唯一性
    
    public Process exec(String command)throws IOException
     在单独的进程中执行指定的字符串命令。 
     command - 一条指定的系统命令。 
     返回:一个新的 Process 对象,用于管理子进程
    Process:
     一个抽象类,进程由操作系统底层完成.
     API并未写明该类有子类
     但是我一直在想抽象方法,怎么能被执行?
     只能说明有子类实现了该方法,在源文件中
     的确有一个类ProcessImpl继承了Process复写了其中方法
    */
    package runtime;
    import java.io.IOException;
    class RuntimeDemo{
     public static void main(String[] args)throws Exception{//抛给JVM,让JVM处理 
       /* 
       Runtime rt = Runtime.getRuntime(); 
       try{
        Process p=rt.exec("F:\\Software\\AIRPLAY\\airplay.exe");//该方法上有异常声明,那么要么throws,要么try...catch
        //打开可执行程序
        //如果在当前目录/指定目录 找不到,则会去path路径下依次查找,以最先找到为准
      
       try{
        Thread.sleep(4000);//由于创建结束的速度太快,因此让主线程暂停一会,在杀,为了在任务管理器看效果
       }
       catch(Exception e){
       }
        
        p.destroy();//杀掉子进程 //也就是说在启动上面的程序后,结束掉
       }
       catch(IOException e){
        e.printStackTrace();
       }
       */
       Runtime  rt = Runtime.getRuntime();
       Process p=rt.exec("notepad.exe RuntimeDemo.java");//可以用notepad(windows记事本)打开java源文件
       
     }
    }

    3.对日期操作:

    package date;
    import java.util.Date;
    import java.text.SimpleDateFormat;//利用该类使日期指定格式输出
                                      //SimpleDateFormat extends DateFormat
    import java.util.Calendar;
    import java.util.GregorianCalendar;                                  
    
    class DateDemo{
       public static void main(String[] args){
        Date d=new Date();
        System.out.println(d);//当前系统时间  
        
        
        SimpleDateFormat sd=new SimpleDateFormat("yyyy年M月dd日 E HH:mm:ss");//用给定的模式和默认语言环境的日期格式符号构造 SimpleDateFormat。
        System.out.println(sd.format(d));//输出 指定格式 的日期
        /*
        public final String format(Date date)
         将一个 Date 格式化为日期/时间字符串。 
          date - 要格式化为时间字符串的时间值。
          返回:已格式化的时间字符串。
        */
       
       
       
       
       
       sd = new SimpleDateFormat("yyyy");//为了只获取年
       System.out.println(sd.format(d));//注意返回为String类型,如果进行运算需要Integer.parseInt(str)->转换,比较繁琐
        
    
       //因此通过Calendar类的子类GregorianCalendar获取年(int),get方法
         //方法一:
         System.out.println(new GregorianCalendar());//该对象中包含了大量日期信息
         System.out.println(new GregorianCalendar().get(GregorianCalendar.YEAR));
         
         //方法二:通过Calendar方法getInstance
         Calendar can=Calendar.getInstance();
         System.out.println(can.get(Calendar.YEAR));
    
         System.out.println(can.get(Calendar.MONTH));//计算机把月从0开始,也就是1月为0月,以此类推.
        
         /*
          如果想得到现实中的月份,必须+1.
          这时候,为了更方便,采用以前曾经在十进制转R进制用到的 查表法
         */
         String[] month={"一月","二月","三月","四月","五月","六月",
                         "七月","八月","九月","十月","十一月","十二月"};
         System.out.println(month[can.get(Calendar.MONTH)]);
         
         /*
         同理美国人把周日当做一周的第一天
             日 一 二 三 四 五 六
               1  2  3  4  5  6  7
      Index 0 1  2  3  4  5  6  7
         */
         String[] week={"","星期日","星期一","星期二","星期三",
                        "星期四","星期五","星期六"};
         System.out.println(week[can.get(Calendar.DAY_OF_WEEK)]);
      }
    }
    日期

    4.Calendar的set和add方法:

    /*
    public abstract void add(int field,int amount)//此方法子类GregorianCalendar实现
        根据日历的规则,为给定的日历字段添加或减去指定的时间量
     
    //以下为set的重载方法
    void set(int field, int value) 
              将给定的日历字段设置为给定值。
              field - 给定的日历字段。
              value - 给定日历字段所要设置的值。 
    
    void set(int year, int month, int date) 
            设置日历字段 YEAR、MONTH 和 DAY_OF_MONTH 的值。 
    
    void set(int year, int month, int date, int hourOfDay, int minute) 
              设置日历字段 YEAR、MONTH、DAY_OF_MONTH、HOUR_OF_DAY 和 MINUTE 的值。 
    
    void set(int year, int month, int date, int hourOfDay, int minute, int second) 
              设置字段 YEAR、MONTH、DAY_OF_MONTH、HOUR、MINUTE 和 SECOND 的值。 
    
    */
    package calendar;
    import java.util.Calendar;
    
     class CalendarDemo{
        
        public static void printCalendar(Calendar can){
        
        System.out.println(can.get(Calendar.YEAR)+"年"
                           +(can.get(Calendar.MONTH)+1)+"月"+
                            can.get(Calendar.DAY_OF_MONTH)+"日");//如果未设定值,将使用当前系统的值(月从0开始计算)
        
        }
        public static void main(String[] args){
            
         Calendar can= Calendar.getInstance();
         
         can.set(Calendar.YEAR,2010);//把日期设定为指定时期
         //2010年3月27日(年为设定值,月(从0开始)和日使用当前系统值)
         printCalendar(can);
    
         can.set(2010,5,13);//传入的实参为6月
         printCalendar(can);
        
    
         //add方法,当前日期:2010-6-13
         can.add(Calendar.DAY_OF_MONTH,-29);
    //13-1=12->31-(29-12-1)=15
         printCalendar(can);//2010年5月15日
        }
    }

    Calendar的set和add方法

    小练习:

    /*
    1.获取任意年的二月有多少天.
    思想:
    方法一:
      1.把年分为闰年和平年:闰年的二月有29天,而平年28天
      2.判断闰年的条件为:
        ①.能被4整除,但不能被100整除的年份都是闰年
        ②.能被400整除的年份是闰年
      对于以上两个条件满足其中一个即可(也就是①||②)
    
    方法二:
      利用Calendar的set,add,get方法
    */
    
    package calendartest;
    import java.util.Calendar;
    class CalendarTest{
        //方法一:
        public static int dayOfFebruary(int year){
          if((year%4==0&&year%100!=0)||(year%400==0))
              return 29;
          else
            return 28;
        }
        public static void main(String[] args){
           
          System.out.println(dayOfFebruary(2013));//28
    
          Calendar can = Calendar.getInstance();
         
          
          //方法二:3月1日的前一天(28/29)
          can.set(2013,2,1);
          can.add(can.DAY_OF_MONTH,-1);
          System.out.println(can.get(Calendar.DAY_OF_MONTH));//28
        }
    }

    5.Math类:

    /*
    //常用方法:
    public static double ceil(double a)
      
    public static double floor(double a)
    
    public static int round(float a)
    public static long round(double a)
    
    
    public static double pow(double a,double b)
    
    
    ※public static double random()
      返回带正号的 double 值,该值大于等于 0.0 且小于 1.0。
      返回值是一个伪随机选择的数,在该范围内(近似)均匀分布。 
    */
                             
    
    package math;
    import java.util.Random;
    class MathDemo{
        
        
        public static void main(String[] args){
        
        //ceil返回大于指定数据的最小整数
         System.out.println("ceil: "+Math.ceil(-0.3)+" "
                                    +Math.ceil(-5.3));//-0.0 -5.0
        
        //floor返回小于指定数据的最大整数
        System.out.println("floor: "+Math.floor(3.2));//3.0
    
        //round:返回结果相当于
        //(int)Math.floor(传入实参 + 0.5f)或(long)Math.floor(传入实参 + 0.5d)
        int i=Math.round(3.67f);//3.67以单精度浮点数传入,不能使用3.67(默认为double)
        long l=Math.round(3.2);
        System.out.println("round: "+l+" " +i);//3 4
        
        //pow
        System.out.println(Math.pow(3,4));//81.0
    
        
        
        //random
        for(int j=0;j<5;++j)
          System.out.println((int)(Math.random()*10+1));//0<=随机数<11
        System.out.println();
    //或利用Random类
            for(int j=0;j<5;++j)
          System.out.println(new Random().nextInt(11));//0<=随机数<11
    
        }
    }

    Math

    6.保留小数任意位练习:

    /*
    给定一个小数
    保留两位小数
    思想:
     1.要把小数转换成字符串便于处理
     2.把小数分割成整数部分和小数部分,便于处理
     3.尽可能的使程序健壮(也就是可能的情况)
    */
    package decimal;
    
    class DecimalTest{
      //保留两位小数
      public static String retainDecimal(double d){
        return retainDecimal(d,2);
      }
      
     
      //保留任意位小数
       public static String retainDecimal(double d,int places){//p为指定保留位数
           String doubleStr=Double.toString(d);
           String[] str=doubleStr.split("\\.");//把小数分割为整数部分(str[0])和小数部分(str[1]),方便处理
         
           char[] ch =str[1].toCharArray();//把小数部分转换成数组
           int len =str[1].length();
           
           if(len==places)//此时该小数恰好有指定的位数
                return doubleStr;     //例如:3.125,3->3.125     
           else
              if(len<places)//不够指定位数:3.1,3->3.100
                 return zeroFill(doubleStr,str[1],places);
              else
                if(ch[places]>'4'){//四舍五入处理
                      
                      double round=Math.pow(0.1,places);//2位+0.01,3位+0.001,4位+0.0001......
                                                   //0.1运算完之后,精度相当高,也就是说0.1的平方并不是0.01,位数更多
                                                     
                      String newDoubleStr=Double.toString(d+round);
                      String[] newStr=newDoubleStr.split("\\.");
                      
                      return  newStr[0]+"."+newStr[1].substring(0,places);
                    }
                 else
                   return str[0]+"."+str[1].substring(0,places);
              
    }
     
     

    //填充零方法 public static String zeroFill(String doubleStr,String str,int places){ StringBuilder sb = new StringBuilder(doubleStr); for(int i=places-str.length();i>0;--i) sb.append('0'); return sb.toString(); }



    public static void main(String[] args){ System.out.println(retainDecimal(99.125) +"\n"+retainDecimal(3.99958,7)); //或利用API中已有的方法: /* public static String format(String format, Object... args) 使用指定的格式字符串和参数返回一个格式化字符串。 */ double d = 3.1465926; String result = String.format("%.2f", d);//类似于C语言中的printf格式的控制 System.out.println(result);//会四舍五入 } }

    保留小数的任意位

  • 相关阅读:
    java时间戳转换日期 和 日期转换时间戳
    通过blob文件导出下载成Excel文件
    三元表达式进化
    Vue切换组件实现返回后不重置数据,保留历史设置操作
    vue 下载文件
    ide打断点,跑到某一行代码,再执行的方法
    Java操作终端的方法
    前端下载本地文件的方法
    java 读取本地json文件
    js 时间戳转换
  • 原文地址:https://www.cnblogs.com/yiqiu2324/p/3053603.html
Copyright © 2011-2022 走看看