Educoder–Java面向對象(第五章)- 包裝類【筆記+參考代碼】

Educoder–Java面向對象(第五章)- 包裝類【筆記+參考代碼】


第一關

編程要求
補充完代碼後,點擊測評,平臺會對你編寫的代碼進行測試,當你的結果與預期輸出一致時,即爲通過。


預期輸出:

裝箱後的結果爲:66.6和66.6

拆箱結果爲:88.88和88.88



參考代碼

package step1;

public class Task {
	public static void main(String[] args) {
		
		//請在此添加實現代碼
		/********** Begin **********/
		//定義float對象
		float f = 66.6f;
		
		//手動裝箱
		Float f1 = new Float(f);
		
		//自動裝箱 
		Float f2 =f;
		
		System.out.println("裝箱後的結果爲:" + f1 + "和" + f2);
		
		//定義一個Double包裝類值爲88.88
		Double d = new Double(88.88);
		
		//手動拆箱
		double d1 = d.doubleValue();
		
		//自動拆箱
		double d2 = d;
		
		System.out.println("拆箱結果爲:" + d1 + "和" + d2);
		
		/********** End **********/
		
	}

}



第二關

編程要求
請仔細閱讀右側代碼,根據方法內的提示,在Begin - End區域內進行代碼補充,具體任務如下:
將int類型數據轉換成其他數據類型。 測試說明 補充完代碼後,點擊測評,平臺會對你編寫的代碼進行測試,當你的結果與預期輸出一致時,即爲通過。

預期輸出:
Integer包裝類:67
double類型:67.0
float類型:67.0
int類型:67



參考代碼

package step2;

public class Task {
	public static void main(String[] args) {

		//請在此添加實現代碼
		/********** Begin **********/
		// 定義int類型變量,值爲67
		int score = 67;

		// 創建Integer包裝類對象,表示變量score的值
		Integer score1 = new Integer(score);

		// 將Integer包裝類轉換爲double類型
		double score2 = score1.doubleValue(); 

		// 將Integer包裝類轉換爲float類型
		float score3 = score1.floatValue();

		// 將Integer包裝類轉換爲int類型
		int score4 = score1.intValue();

		System.out.println("Integer包裝類:" + score1);
		System.out.println("double類型:" + score2);
		System.out.println("float類型:" + score3);
		System.out.println("int類型:" + score4);

		/********** End **********/
		
	}
}




第三關

編程要求
請仔細閱讀右側代碼,根據方法內的提示,在Begin - End區域內進行代碼補充,具體任務如下:

完成基本數據類型與字符串之間的相互轉換。 測試說明:
補充完代碼後,點擊測評,平臺會對你編寫的代碼進行測試,當你的結果與預期輸出一致時,即爲通過。


預期輸出:

str + 12 的結果爲: 78.512

d + 100 的結果爲: 280.2


參考代碼

package step3;

public class Task {
	public static void main(String[] args) {
		double a = 78.5;
        
		//請在此添加實現代碼
		/********** Begin **********/
		//將基本類型a轉換爲字符串
		String str = String.valueOf(a);
        
		System.out.println("str + 12  的結果爲: "+(str + 12));
		
		String str1 = "180.20";
	    // 將字符串str1轉換爲基本類型
		Double d = Double.parseDouble(str1);
	
		System.out.println("d + 100 的結果爲: "+ (d + 100));

		/********** End **********/
		
	} 
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章