JavaEE

java_System,Math类

2019-01-22  本文已影响1641人  会摄影的程序员

1.System类

  • 它不能被实例化,因为构造方法私有化了
  • 它也不能被继承,因为System类中的方法都是静态的,可以通过域名直接访问

1.1 System类中的几个常用方法

1.1.1 exit(int code);

退出JVM

1.1.2 cg();

1.2 getProperty(String PropertyName)

1.3 long currentTimeMillis();

demo:

package com.looc.demo06.demoSystem;

public class TestStringBuffer {
    public void run(){
        StringBuffer sb = new StringBuffer();
        for (int i=0; i<40000; i++){
            sb.append(i);
        }
        System.out.println(sb.toString());
    }
}

package com.looc.demo06.demoSystem;

public class TestString {
    public void run(){
        String str = "";
        for (int i=0; i<40000; i++){
            str+=i;
        }
        System.out.println(str);
    }
}
package com.looc.demo06.demoSystem;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class SystemDemo {
    public static void main(String[] args){
        TestString testString = new TestString();
        TestStringBuffer testStringBuffer = new TestStringBuffer();
        System.out.println(getRunTime(testString)+"秒");
        System.out.println(getRunTime2(testStringBuffer)+"秒");
    }
    
    public static double getRunTime(TestString t){
        long start = System.currentTimeMillis();
        t.run();
        long end = System.currentTimeMillis();
        return (end-start)/1000;
    }
    public static double getRunTime2(TestStringBuffer t){
        long start = System.currentTimeMillis();
        t.run();
        long end = System.currentTimeMillis();
        return (end-start)/1000;
    }
}

输出

01234567891011121314151617......
4.0秒
01234567891011121314151617......
0.0秒

Process finished with exit code 0

2.Math类

  • 不能被继承,重写 因为数学的算法是固定的不需要开发则来重写
  • 常用方法:
  1. max最大值
  2. min最小值
  3. abs取绝对值
  4. random随机数
    范围 [0.0,1.0)
    如果在创建Random的过程中没有传递任何参数 那么java就会将当前的时间作为随机数生成器的种子
package com.cp.random;

import java.util.Random;

public class MyRandom {
  public static void main(String[] args) {
      run();
  }
  public static void run() {
      //每次都不同 int
      Random rand = new Random();
      for(int i = 0;i<10;i++) {
          System.out.println(rand.nextInt(100));
      }
      //每次都一样 int
      Random rands = new Random(47);
      for(int i = 0;i<10;i++) {
          System.out.println(rands.nextInt(100));
      }
      //Long
      Random randLong = new Random();
      System.out.println(""+randLong.nextLong());
      //Double
      Random randDouble = new Random();
      System.out.println(""+randDouble.nextDouble());
  }
}
  1. round 四舍五入
  2. pow求次幂
    Math.pow(9,3)==9^3
  3. ceil 向上取整
  4. floor 向下取整
上一篇下一篇

猜你喜欢

热点阅读