1. 程式人生 > >Math.round(),增強for迴圈,equals方法和==的區別,,instanceof運算子和三目運算子的用法

Math.round(),增強for迴圈,equals方法和==的區別,,instanceof運算子和三目運算子的用法

1.Math.round()

有這樣一個問題,將數字23.4,23.6轉換成int型,得到的新數字是多少?

事實上直接轉換的話得到的數字都是23。但在我們程式設計的過程中有時候需要對數字進行四捨五入取整,那麼顯然上面的直接轉換就不能實現我們的要求。但好在java裡面給我提供了一個可以實現四捨五入的方法,這個方法就是Math.round()。

下面我舉個具體的例子:

double above=6.7;
double blow=6.4;
System.out.print((int)above+","+(int)blow+'\n' );
System.out.print(Math.round(above)+","+Math.round(blow));

從程式碼中我們可以看到第一條輸出語句並沒有使用Math.round()方法,而在第二條語句中則使用了Math.round()的方法。

輸出結果如下:

6,6

7,6

2.增強for迴圈

增強for迴圈的出現是為了簡化我們輸出陣列元素的程式碼量,可以使我們的出錯率更低。使用增強for迴圈時我們不需要知道陣列的長度,這樣我們就不會發生陣列越界的錯誤。下面舉個簡單的例子:

int[] test1= {1,23,43,2,4,5,6,5}
		for(int temp:test1)
			System.out.println(temp);

3.equals用法和==的區別

equals方法和==的區別一般體現在兩個方面:

一是體現在類的比較方面:在類的比較方面equals方法和==是等價的,它們都是比較該類在記憶體中的地址是否相同。

而是體現在字串等變數的比較方面:在這面equals比較的是兩者的內容是否一樣,而==比較的是兩者的來路是否一樣,即在記憶體中的地址是否相同。

point a=new point(3,4);
		point b=new point(3,4);
		point c=a;
		System.out.println(a.equals(b));
		System.out.println(a==b);
		System.out.println(a.equals(c));
		System.out.println(a==c);
		String e=new String("你好");
		String f=new String("你好");
		String g=f;
		System.out.println(e==f);
		System.out.println(e.equals(f));
		System.out.println(e==g);
		System.out.println(e.equals(g));
		/*比較類的時候,equals()方法和==是等價的。它們比較的都是在記憶體中的地址
		 * 而在字串中比較這兩者就有所不同
		 * equals()方法比較的是內容,而==比較的是在記憶體中的地址
		 */

輸出結果:

false
false
true
true
false
true
false

true

4.instanceof運算子

instanceof是一個雙目的運算子,運算子左邊是一個物件,右邊是一個類。當左邊的物件是右邊的類或其子類建立的,返回值是true,否則返回值是false。

package 筆記;
class point{
	private int x;
	private int y;
	point(int a,int b){
	x=a;y=b;
	}
}
class tpoint extends point{
	private int z;
	tpoint(int a,int b,int c){
	super(a,b);
	z=c;
	}
}
public class example5_23_1 {
	public static void main(String[] args) {
        tpoint d=new tpoint(3,5,4);
	System.out.println(d instanceof point);
}

因為d是由point的子類tpoint建立的,所以返回值是true。

5.三目運算子

其基本形式為:關係表示式 ?表示式1 :表示式2

當關系表示式的值為true時,整個表示式的值取表示式1的值,當關系表示式的值為false時,整個表示式的值取表示式二的值。

其中關係表示式1和2還可以巢狀使用三目運算子。

int a1=3,a2=5,a3=6,b1;
		b1=a1<a2?a2:a1<a3?a2:(a1+a2);
		System.out.println(b1);

輸出結果:5