4.Java資料型別
阿新 • • 發佈:2019-01-26
1.Java常見的資料型別:
與C++語言的區別:
1)整型多了一個byte位元組型別
2)C++中,布林型別是bool,而在Java中是boolean
3)String要大寫,它不是基本型別,它是一個類,但它在Java中使用頻率較高,是一個常用型別
4)超大型數值計算(64位以上)有BigInteger型和BigDecimal型
2.各種資料型別佔用的位數
與C++不同的是,char佔兩個位元組!!!
3.變數宣告與定義
Java的變數宣告和定義與C++完全一致
型別+變數名=初始值;
public class DataType { public static void main(String[] args) { String brand="華碩 ASUS"; String type="GTX 1080"; int hz=1569; double length=29.8; double width=13.4; double height=5.25; //列印變數 System.out.println("品牌:" + brand); System.out.println("型號:" + type); System.out.println("核心頻率:" + hz + "MHz"); System.out.println("長寬高:" + length + '\\' + width + '\\' + height); } }
執行結果:
1)使用println函式,自動幫我們換了行
2)可以直接放上變數的名稱,列印時對應打印出變數的值
4.常見錯誤
1)使用未初始化的變數會報錯,對於錯誤可以點選左邊的小紅點檢視提示,並有相應的建議修改,雙擊便修改了
2)賦值時數值溢位,可以通過MAX_VAIUE和MIN_VALUK檢視型別的最值
System.out.println(Integer.MAX_VALUE); System.out.println(Integer.MIN_VALUE); System.out.println(Double.MAX_VALUE); System.out.println(Double.MIN_VALUE);
執行結果:
3)取整錯誤,這與C++相似,例如1.0-0.9不是等於0.1,而是0.09999999998
4)變數命名規則,第一個不能是數字,不能是關鍵字,符號只能是下劃線和美元符號
5.格式化輸出內容
1)println,直接將字串和變數名放在括號內,之間用+號連線,並自帶換行功能
System.out.println("品牌:" + brand);
2)print,與println相似,只是比println少了一個換行的功能
System.out.print("品牌:" + brand + '\n');
3)利用err列印資訊,打印出來的字型是紅色,一般用來列印錯誤資訊,不推薦使用
System.err.println("品牌:" + brand);
4)printf,與C語言一樣
System.out.printf("品牌:%s\n", brand);
5)利用String字串處理
String str1=String.format("品牌:%s", brand);
System.out.println(str1);
具體例項:
public class DataType {
public static void main(String[] args) {
String brand="華碩 ASUS";
String type="GTX 1080";
int hz=1569;
double length=29.8;
double width=13.4;
double height=5.25;
//列印變數
System.out.println("品牌:" + brand);
System.out.println("型號:" + type);
System.out.println("核心頻率:" + hz + "MHz");
System.out.println("長寬高:" + length + '\\' + width + '\\' + height);
System.out.print("品牌:" + brand + '\n');
System.out.print("型號:" + type + '\n');
System.out.print("核心頻率:" + hz + "MHz" + '\n');
System.out.print("長寬高:" + length + '\\' + width + '\\' + height + '\n');
System.err.println("品牌:" + brand);
System.err.println("型號:" + type);
System.err.println("核心頻率:" + hz + "MHz");
System.err.println("長寬高:" + length + '\\' + width + '\\' + height);
System.out.printf("品牌:%s\n", brand);
System.out.printf("型號:%s\n", type);
System.out.printf("核心頻率:%dMHz\n", hz);
System.out.printf("長寬高:%.2f\\%.2f\\%.2f\n", length, width, height);
String str1=String.format("品牌:%s", brand);
String str2=String.format("型號:%s", type);
String str3=String.format("核心頻率:%dMHz", hz);
String str4=String.format("長寬高:%.2f\\%.2f\\%.2f", length, width, height);
System.out.println(str1);
System.out.println(str2);
System.out.println(str3);
System.out.println(str4);
}
}
執行結果:
注意,在printf中
1)可以使用%.nf來指定輸出小數點後面n位數字
2)使用%nd來指定輸出n個字元,且是右對齊的,用%-nd是左對齊,一般用來對齊