java 數據Number、Math

一個初出茅廬的小子與你們共享一些關於NumberMath的使用,因水平有限,不免有寫的不完善的地方,嘻嘻。看完以後,但願能夠留下你珍貴的指導意見。html

The Numbers Classesjava

在寫代碼的時候,也許會使用到java 各類的基本數據類型,以下:api

int i = 500;多線程

float gpa = 3.65f;oracle

byte mask = 0xff;app


然而,在面向對象開發的過程,咱們更倡導你使用對象來代替各類的基本數據類型,而java也爲各類基本數據類型提供了wrapper class(包裝類)——這些wrapper class封裝了對應的基本數據。一般,編譯器會爲咱們完成這種封裝——換句話說就是,若是一個方法須要Object類型的參數,而實際提供的值確實23等數值,這時編譯器會把23等數值封裝成對應的wrapper class;相似,若是一個方法須要基本數據類型的參數,而實際提供的卻似Object類型,這時編譯器會Object類型的參數拆成幾本數據類型——而這就所爲的「自動拆裝箱原理」。dom

接着給出一個自動拆裝箱的demoide

Integer x, y;
x = 12;
y = 15;
System.out.println(x+y);
以上爲x、y變量賦int 值,編譯器會自動將x、y封裝成Integer對象類型;在println()裏,爲了進行基本的算術處理,編譯器會自動將x、y變量拆成int的基本數據類型。
 
 
 
 
全部基本數據的wrapper class都是抽象類Number的子類

附:在這裏,有四個Number的子類並無討論。BigDecimal 和 BigInteger 是用於高精度的運算;AtomicInteger 和 AtomicLong 用於多線程程序裏。
 
 
下面給出使用wrapper class 而不使用基本數據類型的理由:
一、可用在須要Object類型參數的方法裏(經常使用於操做集合的數據)
二、在類裏可以使用各類常量(如MIN_VALUEMAX_VALUE),能夠提供各類數據的上下界限(範圍)。
三、可使用wrapper class的對象方法,進行各類值與基本數據類型的相互轉換,如String類型的相互轉換,還能夠與各類進制的數據進行相互裝換(二進制binary、八進制octal、十進制decimal、十六進制hexadecimal)
 
 
下表列出了各個wrapper class都具備的方法(Number 類的方法)

Methods  Implemented by all Subclasses of Number函數

方法工具

描述

byte byteValue()
short shortValue()
int intValue()
long longValue()
 float floatValue()
 double doubleValue()

Number對象轉換成對應的基本數據類型

int compareTo(Byte anotherByte)
 int compareTo(Double anotherDouble)
 int compareTo(Float anotherFloat)
 int compareTo(Integer anotherInteger)
 int compareTo(Long anotherLong)
 int compareTo(Short anotherShort)

Number對象的值與參數anotherXxx的值進行比較

boolean equals(Object obj)

判斷Number對象和參數Object是否相同。

當兩個對象不爲空且數據類型和值都一致的狀況下,才返回true

若是判斷的是DoubleFloat類型,則還須要一些額外的參數,詳情可參考java API的官方文檔。

對於與String類型的數據與及各類進制數據之間的裝換,每一個Number(在這指其子類)都有着相對應的方法。下表列出了Integer對象與String數據和進制之間相互轉換的方法。其餘的Number類都與之相似。

Integer類的轉換方法

方法

描述

static Integer decode(String s)

將String解碼爲Integer。String數據能夠是十進制、八進制或者十六進制。

static int parseInt(String s)

返回一個int值,String只能是十進制的數據。

static int parseInt(String s, int radix)

將指定進制的String數據轉換成int值。參數radix指多少進制(能夠是二、八、10或者16)

String toString()

將Integer數據轉成String類型

static String toString(int i)

返回一個指定整數的String對象

static Integer valueOf(int i)

返回一個表示指定的int值的Integer實例。

static Integer valueOf(String s)

返回String數據的Integer對象

static Integer valueOf(String s, int radix)

將指定進制的String數據轉換爲Integer類型。如當s=」333」,radix=8時,會返回數據爲219的Integer實例。

 
 

格式化輸出各類數據

一直以來,也許你都是在使用標準輸出(System.out)輸出各類數據,之因此能夠這樣作,是由於全部Number數據均可以轉換成String類型。然而,有時候你可能須要更好地控制數據的輸出,則須要使用java提供的其餘方法。

printf()和format()方法

在java.io包裏,有一個PrintStream類,此類提供了兩個方法(printf()和format())來取代print()和println()。printf和format方法除了名字不同以外,其他用法一致。同時由於System.out本事是一個PrintStream對象,因此你能夠在原來使用print()和println()的位置用printf()或者format()方法來代替——System.out.format(.....);

其方法原型以下:

    public PrintStream format(String format, Object... args);
    public PrintStream printf(String format, Object... args);
參數format指定輸出的格式(字符竄的格式),而args則是輸出格式裏的數據(參數列表)。
爲了說明它的用法,能夠看一下這個簡單的例子:

System.out.format("The value of "+ "the float variable is " + "%f, while the value of the "
                           + "integer variable is %d, " + "and the string is %s", floatVar, intVar, stringVar);
 
 

   格式說明由「%+轉換符」組成,轉換符是一個指定輸出數據類型的字符。同時,你能夠在「%」和轉換符之間有選擇地添加其餘標記。想了解更多關於轉換符標記的信息,能夠參閱java.util.Formatter。下面給出一個基本用法的例子:

int i = 461012;
System.out.format("The value of i is: %d%n", i);

「%d」表明了十進制數據(在這裏值i),「%n」表明了輸出換行,因此其輸出以下:

    The value of i is: 461012
爲了適應各地語言的使用習慣,java重載了printf和format方法,以下:
    public PrintStream format(Locale l, String format, Object... args)
 
 
如在法國,輸出的帶有小數的數據時,是用「,」劃分整數和小數的,以下面的代碼:
float floatVar = 123.37f;
int intVar = 123;
      StringstringVar = "123";
      System.out.format(Locale.FRANCE, "The value of the float " + "variable is %f, while the "
                           + "value of the integer variable " + "is %d, and the string is %s%n", floatVar, intVar, stringVar);
 
 

其輸出以下:

   The value of the float variable is 123,370003, while the value of the integer variable is 123, and the string is123

 
 
 
 

Demo:格式化輸出

在這個Demo裏,使用到各類經常使用的轉化符和flags,具體解釋以下表:(更多格式可參閱java.util.Formatter

Converters and Flags Used indemo.java

轉換符

Flag

說明

d


十進制數據

f


浮點數據

n


換行符。注意是用「%n」,而不是「\n」.

tB,tb


‘t’指日期/時間的轉換(下同)’B’指月份全稱(January)’b’指月份的簡稱(Jan)

ty, tY


格式年份,‘y’格式化時帶前導零的兩位數,即00 – 99;’Y’指格式化時帶前導零的四位數(至少),如0096或者2013。

tm


格式月份,’m’指格式時帶前導零的兩位數,即01 ~ 13.

td, te


‘t’指日期/時間的轉換,’d’一個月中的天數,在格式化時帶前導零的兩位數,即01 – 31;‘e’指格式化爲兩位數,即1 – 31

tltk


格式小時數,’l’12小時制(1 ~ 12),’k’24小時制(0 ~ 23)。

tM


格式分鐘數,’M’指格式化時帶前導零的兩位數,即00 ~ 59

tS


格式化秒,格式化時帶前導零的兩位數,即00 - 60"60" 是支持閏秒所需的一個特殊值)。

tp


特定於語言環境的上午或下午,標記以小寫形式表示,例如 "am" "pm"

tD


A date & time conversion—date as %tm%td%ty


08

8個字符寬度,寬度不足在頭部以「0」填充


+

包含符號位(正數+或負數—)


,

組分隔符


-

左對齊(默認是右對齊)


.3

保留3位小數


10.3

表示10個字符寬度,保留三位小數(默認右對齊)


import java.util.Calendar;
import java.util.Locale;
public class IntegerText {
    public static void main(String[] args) {
        long n = 461012;
        System.out.format("%d%n", n); // --> "461012"
        System.out.format("%08d%n", n); // --> "00461012"
        System.out.format("%+8d%n", n); // --> " +461012"
        System.out.format("%,8d%n", n); // --> " 461,012"
        System.out.format("%+,8d%n%n", n); // --> "+461,012"
        double pi = Math.PI;
        System.out.format("%f%n", pi); // --> "3.141593"
        System.out.format("%.3f%n", pi); // --> "3.142"
        System.out.format("%10.3f%n", pi); // --> "     3.142"
        System.out.format("%-10.3f%n", pi); // --> "3.142"
        System.out.format(Locale.FRANCE, "%-10.4f%n%n", pi); // --> "3,1416"
        Calendar c = Calendar.getInstance();
        System.out.format("%tB %te, %tY%n", c, c, c); // --> "May 29, 2006"
        System.out.format("%tl:%tM %tp%n", c, c, c); // --> "2:34 am"
        System.out.format("%tD%n", c); // --> "05/29/06"
    }
}

TheDecimalFormat Class

可使用java.text.DecimalFormat格式化十進制數字的輸出,包括前/後導零、先後綴、組分隔符、小數點。儘管使用DecimalFormat能夠靈活控制輸出的格式,另外一面它也增長了代碼的複雜度。以下:經過模式patten構造DecimalFormat的對象myFormatter,接着調用format()方法(從NumberFormat繼承過來的),格式化輸出字符串。


import java.text.*;
public class DecimalFormatDemo {
    static public void customFormat(String pattern, double value) {
        DecimalFormat myFormatter = new DecimalFormat(pattern);
        String output = myFormatter.format(value);
        System.out.println(value + "  " + pattern + "  " + output);
    }
    static public void main(String[] args) {
        customFormat("###,###.###", 123456.789);    //-->123456.789  ###,###.###  123,456.789
        customFormat("###.##", 123456.789);         //-->123456.789  ###.##  123456.79
        customFormat("00.000", 123.7876);           //-->123.7876  00.000  123.788
        customFormat("$###,###.###", 12345.67);     //-->12345.67  $###,###.###  $12,345
    }
}

下表解釋了上面每一行代碼的格式輸出:

DecimalFormat.java輸出說明

數值

Pattern

輸出

說明

123456.789

###,###.###

123,456.789

‘#’ 表明了一個阿拉伯數字,‘,’爲組分隔符,‘.’用於分割整數和小數

123456.789

###.##

123456.79

數值有三位小數,而模式裏只用兩個,會經過四捨五入保留兩位小數

123.78

000000.000

000123.780

0’表明了一個阿拉伯數字,位數不足須要在前或後一零補充,注意其與‘#’的區別。

12345.67

$###,###.###

$12,345.67

以美圓符號‘$’開頭,保留三位小數,且組分割爲3

tips:組分隔符「,」一般用於千位,可是在某些國家/地區中回用於分隔萬位(如中國)。分組大小是分組字符之間的固定數字位數,例如100,000,000 是 3,而 1,0000,0000 則是 4。若是使用具備多個分組字符的模式,則最後一個分隔符和整數結尾之間的間隔纔是使用的分組大小。因此 "#,##,###,####" == "######,####" =="##,####,####"。 即「123456.789」的模式爲「###,#,##.###」,其輸出爲「12,34,56.789」。


基本算數運算以外

java除了支持各類基本的算術運算(+, -, *, /, 和 %)以外,也爲各類複雜的數學運算提供了工具類Math。經過Math類能夠完成指數、對數、反三角函數等複雜的運算。

因爲Math類的方法都是靜態的,你能夠在類裏直接調用Math類的方法,以下:

  Math.cos(angle);

tips:可使用static import靜態導入Math類,如此便不用在每一個方法下上Mathimport static java.lang.Math.*;
接着就能夠直接在方法體裏經過Math類的方法名調用Math類對應的方法:
               cos(angle);

常量與基本算術方法

Math類裏包含兩個常量:

  • Math.E,     天然底數e

  • Math.PI,圓周率

Math類包含了超過40個的靜態方法,爲了分類來談,先列出Math裏的基本算術方法:

Math的基本算術方法

方法

描述

double abs(double d)
float abs(float f)
int abs(int i)
long abs(long lng)

返回參數的絕對值

double ceil(double d)

取得大於或等於參數的最小整數,並以double類型返回

double floor(double d)

取得小於或等於參數的最大整數,並以double類型返回

double rint(double d)

取得最接近參數的某一整數(相似於四捨五入),並以double類型返回

long round(double d)
int round(float f)

返回最接近參數的long/int

double min(double arg1, double arg2)
float min(float arg1, float arg2)
int min(int arg1, int arg2)
long min(long arg1, long arg2)

返回兩個數中較小的那一個

double max(double arg1, double arg2)
float max(float arg1, float arg2)
int max(int arg1, int arg2)
long max(long arg1, long arg2)

返回兩個數中較大的那一個

BasicMathDemo演示瞭如何去使用Math的基本算術方法:

public class BasicMathDemo {
     public static void main(String[] args) {
            double a = -191.635;
            double b = 43.74;
            int c = 16, d = 45;
            System.out.printf("The absolute value " +
                              "of %.3f is %.3f%n",
                              a, Math.abs(a));      //-->The absolute value of -191.635 is 191.635
            System.out.printf("The ceiling of " +
                              "%.2f is %.0f%n",
                              b, Math.ceil(b));     //-->The ceiling of 43.74 is 44
            System.out.printf("The floor of " +
                              "%.2f is %.0f%n",
                              b, Math.floor(b));    //-->The floor of 43.74 is 43
            System.out.printf("The rint of %.2f " +
                              "is %.0f%n",
                              b, Math.rint(b));     //-->The rint of 43.74 is 44
            System.out.printf("The max of %d and " +
                              "%d is %d%n",
                              c, d, Math.max(c, d));//-->The max of 16 and 45 is 45
            System.out.printf("The min of of %d " +
                              "and %d is %d%n",
                              c, d, Math.min(c, d));//-->The min of of 16 and 45 is 16
        }
}


Math裏指數與對數運算:

下表列出了在Math裏關於指數與對數運算的方法:

指數、對數運算的方法

方法

描述

double exp(double d)

返回天然底數ed次方冪的值

double log(double d)

返回d值的天然對數(底數是e)。相似的有log10(double a)

double pow(double base, double exponent)

返回baseexponent次方的值

double sqrt(double d)

返回d的算術平方根

Demo:ExponentialDemo 
public class ExponentialDemo {
    public static void main(String[] args) {
        double x = 11.635;
        double y = 2.76;
        System.out.printf("The value of " +
                          "e is %.4f%n",
                          Math.E);      //-->The value of e is 2.7183
        System.out.printf("exp(%.3f) " +
                          "is %.3f%n",
                          x, Math.exp(x));//-->exp(11.635) is 112983.831
        System.out.printf("log(%.3f) is " +
                          "%.3f%n",
                          x, Math.log(x));//-->log(11.635) is 2.454
        System.out.printf("pow(%.3f, %.3f) " +
                          "is %.3f%n",
                          x, y, Math.pow(x, y));//-->pow(11.635, 2.760) is 874.008
        System.out.printf("sqrt(%.3f) is " +
                          "%.3f%n",
                          x, Math.sqrt(x));//-->sqrt(11.635) is 3.411
    }
}


Math裏三角函數運算

下表列出了Math裏關於三角函數的方法,須要注意的是,這些方法的參數都是以弧度制來表示的——換句話說就是,你須要將角度轉換爲弧度。可使用方法toRadians(),將角度轉換爲弧度。

三角函數運算的方法

方法

描述

double sin(double d)

返回角的三角正弦值

double cos(double d)

返回角的三角餘弦值

double tan(double d)

返回角的三角正切值

double asin(double d)

返回一個值的反正弦值;返回的角度範圍在 -pi/2 pi/2  之間。

double acos(double d)

返回一個值的反餘弦值;返回的角度範圍在 0.0 pi之間。

double atan(double d)

返回一個值的反正切值;返回的角度範圍在 -pi/2 pi/2  之間。

double atan2(double y, double x)

將矩形座標 (x, y) 轉換成極座標 (r, theta),返回所得角theta

double toDegrees(double d)
 double toRadians(double d)

角度和與弧度的相互轉換方法

DemoTrigonometricDemo, 計算45度角的三角函數值:

public class TrigonometricDemo {
     public static void main(String[] args) {
            double degrees = 45.0;
            double radians = Math.toRadians(degrees);
                                                                 
            System.out.format("The value of pi " +
                              "is %.4f%n",Math.PI);
            //-->The value of pi is 3.1416
            System.out.format("The sine of %.1f " +
                              "degrees is %.4f%n",
                              degrees,Math.sin(radians));
            //-->The sine of 45.0 degrees is 0.7071
            System.out.format("The cosine of %.1f " +
                              "degrees is %.4f%n",
                              degrees, Math.cos(radians));
            //-->The cosine of 45.0 degrees is 0.7071
            System.out.format("The tangent of %.1f " +
                              "degrees is %.4f%n",
                              degrees, Math.tan(radians));
            //-->The tangent of 45.0 degrees is 1.0000
            System.out.format("The arcsine of %.4f " +
                              "is %.4f degrees %n",
                              Math.sin(radians), Math.toDegrees(Math.asin(Math.sin(radians))));
            //-->The arcsine of 0.7071 is 45.0000 degrees
            System.out.format("The arccosine of %.4f " +
                              "is %.4f degrees %n",
                              Math.cos(radians),  Math.toDegrees(Math.acos(Math.cos(radians))));
            //-->The arccosine of 0.7071 is 45.0000 degrees
            System.out.format("The arctangent of %.4f " +
                              "is %.4f degrees %n",
                              Math.tan(radians), Math.toDegrees(Math.atan(Math.tan(radians))));
            //-->The arctangent of 1.0000 is 45.0000 degrees
        }
}

隨機數

      Math類的random()方法能夠產生大於等於0.0且小於1.0的(僞)隨機數(0 <= Math.random()<1),如此,你便能利用這個函數產生各中範圍的隨機數,如

要產生0~9的隨機數:

int number = (int)(Math.random() * 10);       //(0 <= number < 10)

如產生5~9的隨機數:

int number = (int)(Math.random() * 5) + 5;

附:使用Math.random()能夠產生一個隨機數。若是須要產生一系列隨機數,能夠建立 java.util.Random的對象,並調用對應的方法。