Java 换行字符缩进?(爪哇)
我试图使用\n创建字符串列表,但每当我添加多个字符串时,字符串缩进到上一个字符串的点,因此示例输出为:Java 换行字符缩进?(爪哇),java,string,newline,indentation,Java,String,Newline,Indentation,我试图使用\n创建字符串列表,但每当我添加多个字符串时,字符串缩进到上一个字符串的点,因此示例输出为: 0 hello nain 1 test nain 2 huh nain 我不知道它为什么这样做。下面是我创建字符串的代码: String[] posts = currentTopic.getMessages("main"); //String[] postsOutput =
0 hello nain
1 test nain
2 huh nain
我不知道它为什么这样做。下面是我创建字符串的代码:
String[] posts = currentTopic.getMessages("main");
//String[] postsOutput = new String[posts.length];
String postsOutput = "0 " + posts[0];
for(int i = 1; i < posts.length; i++){
postsOutput += "\n" + i + " " + posts[i];
//postsOutput[i] = i + posts[i];
}
sc.close();
return postsOutput;
String[]posts=currentTopic.getMessages(“main”);
//String[]postsOutput=新字符串[posts.length];
字符串postsOutput=“0”+posts[0];
for(int i=1;i
我还尝试将\n移动到追加的末尾,但结果仍然相同。任何帮助都将不胜感激
谢谢看起来您所处的系统中“\n”刚刚停止(换行),并且您缺少所需的回车
这不应该是您自己需要注意的事情:
line.separator
属性正在根据主机操作系统进行调整,使其行为类似于system.out.println
尝试\r\n,即回车和换行。您应该使用属性system.getProperty(“line.separator”)
,保存基础系统换行符的
String newline = System.getProperty("line.separator");
String[] posts = currentTopic.getMessages("main");
//String[] postsOutput = new String[posts.length];
String postsOutput = "0 " + posts[0];
for(int i = 1; i < posts.length; i++){
postsOutput += newline + i + " " + posts[i];
//postsOutput[i] = i + posts[i];
}
sc.close();
return postsOutput;
String newline=System.getProperty(“line.separator”);
字符串[]posts=currentTopic.getMessages(“main”);
//String[]postsOutput=新字符串[posts.length];
字符串postsOutput=“0”+posts[0];
for(int i=1;i
我认为这是一个很好的例子,因为%n
总是使用系统特定的行分隔符。在循环中写入:
postsOutput += String.format("%n%d %d", i, posts[i]);
+1.@nain33可以使用
\r\n
。CR+LF。ASCII上的字符分别为13和10。应该有一些Java OS不可知变量可以适应这一点,不是吗?使用System.getProperty(“line.separator”)
@Alex:yes,刚刚想好了^ ^你也可以试试BufferedWriter
。它有一个newLine
方法。无论如何,它使用System.getProperty(“line.separator”)
正如@Alex所说:)使用System.getProperty(“line.separator”)
而不是换行符。顺便说一句,不要用“+”运算符附加字符串。使用StringBuffer或StringBuilder,尤其是在循环中。。。您的代码将生成大量无用的对象(字符串实例)。不要使用StringBuffer,它是不同步的。