總網頁瀏覽量

2012年5月24日 星期四

JAVA 其它類別


其他類:
System 類中的方法和屬性都是靜態類型,final類別不可實例化與繼承
in: 標準輸入,默認是鍵盤
out: 標準輸出,默認是螢幕

獲取系統屬性訊息: Properties getProperties();

class Main{
    public static void main(String[] args){
        //ProprtiesHashtable的子類,也就是Map集合的一個子類對象
        //可以通過map的方法取出該集合中的元素
        //該集合中存儲的都是字串,沒有泛型定義
        Properties prop = System.getProperties();
        for(Object obj: prop.keySet()){
            String value = (String)prop.get(obj);
            System.out.println(obj + "::" + value);
        }
        //在系統中自一些自有訊息
        System.setProperty("mykey", "myvalue");
        //獲取指定屬性訊息
        String value = System.getProperty("os.name");
        System.out.println("value = " + value);
    }
}
//添加系統屬性訊息
//java -D"key"="value" "class name"

Runtime
該類沒有提供建構子,所以不可實例化,表示該類中的方法為靜態,但是發現該類中還有非靜態方法,說明該類中肯定還有提供某靜態方法其傳回值為本類物件(單例設計模式),這樣才能夠取得物件操作非靜態方法

class Main{
    public static void main(String[] args) throws Exception{
        Runtime mRuntime = Runtime.getRuntime();
        //執行路徑中exe程式
        Process p = mRuntime.exec("C:\\android-sdk-windows\\SDK Manager.exe");
        Thread.sleep(4000);
        p.destroy(); //殺掉子進程
    }
}

Data
class Main{
    public static void main(String[] args) throws Exception{
        Date date = new Date();
        System.out.println(date);
       
        //將模式封裝到SimpleDateformat
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd hh:mm:ss");
        //調用format方法讓模式格式化指定Data物件
        String time = sdf.format(date);
        System.out.println(time);
    }
}


Calendar
//取得任意年的二月有多少天
/*
 * 根據指定年設置某一個時間
 * c.set(year, 2, 1) 某一年的31
 * c.add(Calendar, DAY_OF_MONTH, -1) 往前推一天 2月最後一天
 * */
class Hello{
     public static void main(String[] args){
         Calendar c = Calendar.getInstance();
        
         String[] mons = {"1", "2","3","4","5","6","7","8","9","10","11","12",};
         int index = c.get(Calendar.MONTH);
        
         sop(c.get(Calendar.YEAR) + "");
         sop(mons[index] + "");
         sop(c.get(Calendar.DAY_OF_MONTH) + "");
         sop("星期" + (c.get(Calendar.DAY_OF_WEEK) - 1));
     }
     public static void sop(Object obj){
         System.out.println(obj);
     }
}


Math and Random
class Hello{
     public static void main(String[] args){
         //ceil返回最接近大於指定數據的整數
         sop(Math.ceil(-16.32));//-16
         sop(Math.ceil(16.32));//17
         sop(Math.round(5.39));//5
        
         sop(Math.floor(-16.32));//-17
         sop(Math.floor(16.32));//16
         sop(Math.pow(2, 3));//8
        
         Random r = new Random();
         for(int x = 0; x <10; x++){
              //int d = (int)(Math.random()*10 + 1);
              //sop(d);
              sop(r.nextInt(10) + 1);
         }
     }
     public static void sop(Object obj){
         System.out.println(obj);
     }
}

產生亂數
Random rand = new Random(47);
int i = rand.nextInt(100) + 1; // => 59
int j = rand.nextInt(100) + 1; // => 56

還有nextFloat()、nextLong()、nextDouble()等等



沒有留言:

張貼留言