語言輸出換行符號是什麼_Java格式化輸出
阿新 • • 發佈:2021-01-18
技術標籤:語言輸出換行符號是什麼
步驟1:格式化輸出步驟2:printf和format步驟3:換行符步驟4:總長度,左對齊,補0,千位分隔符,小數點位數,本地化表達步驟5:練習-黃鶴步驟6:答案-黃鶴
步驟 1 : 格式化輸出
如果不使用格式化輸出,就需要進行字串連線,如果變數比較多,拼接就會顯得繁瑣
使用格式化輸出,就可以簡潔明瞭
%s 表示字串
%d 表示數字
%n 表示換行
package digit; public class TestNumber { public static void main(String[] args) { String name ="蓋倫"; int kill = 8; String title="超神"; //直接使用+進行字串連線,編碼感覺會比較繁瑣,並且維護性差,易讀性差 String sentence = name+ " 在進行了連續 " + kill + " 次擊殺後,獲得了 " + title +" 的稱號"; System.out.println(sentence); //使用格式化輸出 //%s表示字串,%d表示數字,%n表示換行 String sentenceFormat ="%s 在進行了連續 %d 次擊殺後,獲得了 %s 的稱號%n"; System.out.printf(sentenceFormat,name,kill,title); } }
步驟 2 : printf和format
printf和format能夠達到一模一樣的效果,如何通過eclipse檢視java原始碼 可以看到,在printf中直接呼叫了format
package digit; public class TestNumber { public static void main(String[] args) { String name ="蓋倫"; int kill = 8; String title="超神"; String sentenceFormat ="%s 在進行了連續 %d 次擊殺後,獲得了 %s 的稱號%n"; //使用printf格式化輸出 System.out.printf(sentenceFormat,name,kill,title); //使用format格式化輸出 System.out.format(sentenceFormat,name,kill,title); } }
步驟 3 : 換行符換行符就是另起一行 --- 'n' 換行(newline)回車符就是回到一行的開頭 --- 'r' 回車(return)
在eclipse裡敲一個回車,實際上是回車換行符
Java是跨平臺的程式語言,同樣的程式碼,可以在不同的平臺使用,比如Windows,Linux,Mac
然而在不同的作業系統,換行符是不一樣的
(1)在DOS和Windows中,每行結尾是 “rn”;
(2)Linux系統裡,每行結尾只有 “n”;
(3)Mac系統裡,每行結尾是隻有 "r"。
為了使得同一個java程式的換行符在所有的作業系統中都有一樣的表現,使用%n,就可以做到平臺無關的換行
package digit;
public class TestNumber {
public static void main(String[] args) {
System.out.printf("這是換行符%n");
System.out.printf("這是換行符%n");
}
}
步驟 4 : 總長度,左對齊,補0,千位分隔符,小數點位數,本地化表達
其他常用的格式化方式
package digit;
import java.util.Locale;
public class TestNumber {
public static void main(String[] args) {
int year = 2020;
//總長度,左對齊,補0,千位分隔符,小數點位數,本地化表達
//直接列印數字
System.out.format("%d%n",year);
//總長度是8,預設右對齊
System.out.format("%8d%n",year);
//總長度是8,左對齊
System.out.format("%-8d%n",year);
//總長度是8,不夠補0
System.out.format("%08d%n",year);
//千位分隔符
System.out.format("%,8d%n",year*10000);
//小數點位數
System.out.format("%.2f%n",Math.PI);
//不同國家的千位分隔符
System.out.format(Locale.FRANCE,"%,.2f%n",Math.PI*10000);
System.out.format(Locale.US,"%,.2f%n",Math.PI*10000);
System.out.format(Locale.UK,"%,.2f%n",Math.PI*10000);
}
}
更多內容,點選瞭解: https://how2j.cn/k/number-string/number-string-foramt/320.html