通過只輸入一次打印4個整數的結果'system.out.println'。
很簡單,您需要在您要打印的文本中添加一個換行字符。在大多數機器上,這由特殊字符\n
表示。
String output = a + "\n"
+ b + "\n"
+ c + "\n"
+ d;
System.out.println(output);
但是有平臺獨立方式像什麼方法System.lineSeparator()
(documentation)的回報。像:
String lineSeparator = System.lineSeparator();
String output = a + lineSeparator
+ b + lineSeparator
+ c + lineSeparator
+ d;
System.out.println(output);
另外,您可以使用System.out.printf
方法(documentation),它代表 「打印格式」。它具有參數%n
,它創建一個新行,內部也使用System.lineSeparator()
。
System.out.printf("%d%n%d%n%d%n%d%n", a, b, c, d);
的%d
是許多像int
的佔位符。它用後面列出的參數替換所有佔位符。
這裏是方法接受的所有參數的完整列表:Formatter-Syntax
如果你看一下使用流和Lambda表達式一個的Java 8的解決方案,那麼你可以使用此代碼(documentation):
IntStream.of(a, b, c, d).forEachOrdered(System.out::println);
它首先創建一個流(像在這種情況下,一個容器)牽着你的變量,然後調用打印方法其每個的元素。請注意,代碼本身稱爲打印方法現在4次,不是只有一次。但它看起來相當緊湊。
您可以查看「相當於」下面的代碼:
int[] values = new int[]{a, b, c, d};
for (int value : values) {
System.out.println(value);
}
要在此格式化,您可以在鍵盤上使用「空格鍵」;) – azro
嘗試使用'System.out.println(a +「\ n」+ b +「\ n」+ c +「\ n」 + d);' –
這就是我正在尋找YCF_L,我如何投票給你哈哈?是的,我用空間來格式化代碼,但我需要在每一行使用空間每次? –