gpt4 book ai didi

java - 有什么方法可以阻止 Java 在控制台输出中自动创建新行?

转载 作者:行者123 更新时间:2023-11-29 08:30:07 24 4
gpt4 key购买 nike

我一个月前开始学习 Java,并且一直使用 Eclipse 作为工作区。虽然我喜欢它的布局,但我一直对控制台输出的内容感到困惑。具体来说,尽管代码中没有要求创建新行,但控制台会自动在输出中创建新行。

例如,像这样:

     public class myClass
{
public static void main(String args[])
{
int [] array = {10, 20, 30, 40, 50};
for(int x : array)
{
System.out.println(x + ", ");
}
}
}

将打印以下内容:

10,

20,

30,

40,

50,

有什么办法可以阻止这种情况发生吗?我不希望 future 的项目在行与行之间有如此奇怪的间距。

最佳答案

这不是 Eclipse。它是您调用的 Java 方法 System.out.println:

public void println(String s)

Terminates the current line by writing the line separator string. The line separator string is defined by the system property line.separator, and is not necessarily a single newline character ('\n').

public void print(String s)

Prints a string. If the argument is null then the string "null" is printed. Otherwise, the string's characters are converted into bytes according to the platform's default character encoding, and these bytes are written in exactly the manner of the write(int) method.

如果您想在一行中打印所有数字,请改用 print()

一个更短的方法是:

String output = String.join(",", array);  // Java8

关于java - 有什么方法可以阻止 Java 在控制台输出中自动创建新行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49118686/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com