System.out.print("I have a question, can you assist me?");
System.out.println();
System.out.println("How can I make a gap between these two statements?");
我尝试使用println()
,以为它会创建一行空白,但实际上并没有。
System.out.print("I have a question, can you assist me?");
System.out.println();
System.out.println("How can I make a gap between these two statements?");
我尝试使用println()
,以为它会创建一行空白,但实际上并没有。
请尝试:
public class Main {
public static void main(String args[]) {
System.out.println("I have a question, can you assist me?\n");
System.out.println("How can I make a gap between these two statements?");
}
}
P.S. \n
是换行分隔符,在Windows机器上可以正常工作。为了实现真正的跨平台分隔符,请使用以下方法之一:
System.out.print("Hello" + System.lineSeparator()); // (for Java 1.7 and 1.8)
System.out.print("Hello" + System.getProperty("line.separator")); // (Java 1.6 and below)
以下是正在发生的事情。
System.out.print("I have a question, can you assist me?");
您现在已经打印了一堆字符,全部在同一行上。由于使用了print
并且没有显式地打印换行符,下一个要打印的字符也将放在同一行上。
System.out.println();
这将打印一个换行符 ('\n'
),它与打印空白行是不同的。相反,它会导致下一个要打印的字符进入当前行以下的一行。
System.out.println("How can I make a gap between these two statements?");
由于您刚刚打印了一个换行符,所以这段文本将会出现在“我有一个问题”的下一行。此外,由于您调用了println
,如果您在此之后立即打印任何内容,它将会出现在新的一行而不是同一行。
要在两个语句之间插入一个空行,您可以这样做(我知道,我知道,不是完全跨平台的,但这只是一个非常简单的例子):
System.out.println("I have a question, can you assist me?");
System.out.println();
System.out.println("How can I make a gap between these two statements?");
由于您现在在两行之间打印了两个换行符,因此您将实现所需的间隔。
Just use println consistently:
System.out.println("I have a question, can you assist me?");
System.out.println();
System.out.println("How can I make a gap?");
Note: println
uses the platform default end-of-line sequence.
Use String.format:
String msg = "I have a question, can you assist me?%n%nHow can " +
"I make a gap?%n";
System.out.print(String.format(msg));
Note: %n
means the platform default end-of-line sequence.
Note: there is a convenience printf
method in the PrintWriter
interface that does the same thing as String.format
Manually insert the appropriate end-of-line sequence into the string; see the end of @userlond's answer for examples.
如果你想在Java中留下单行空格,你可以使用
System.out.println("");
但是如果你想在Java中保留多行空格,可以使用
System.out.println("/n/n/n/n");
这意味着每个'/n'代表一行。
使用: system.out.println("\n");
\n可以将光标移至下一行。
System.out.print("Hello \n\n\n\n");
System.out.print("World");
这个怎么样?
public class Main {
public static void main(String args[]) {
System.out.println("Something...");
System.out.printf("%n"); // Not "\n"
System.out.println("Something else...");
}
}
"%n" 应该是跨平台友好的。
"
System.out.println("");
orSystem.out.print("I have a question, can you assist me?\n");
- MadProgrammer