Reputation: 135
I am trying to use \n to create a list of strings but whenever I add more than one string, the string indents up to the point of the previous string so an example output would be:
0 hello nain
1 test nain
2 huh nain
I don't know why its doing this. Here's the code where I create the string:
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;
I also tried moving the \n to the end of the appending but the result is still the same. Any help would be appreciated.
Thanks
Upvotes: 2
Views: 10233
Reputation: 16403
I think this is a good example to use String.format because %n
always uses the system specific line seperator. Inside your loop write:
postsOutput += String.format("%n%d %d", i, posts[i]);
Upvotes: 2
Reputation: 25613
You should use the property System.getProperty("line.separator")
, that holds the underlying system newline character.
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;
Upvotes: 1
Reputation: 2646
that looks like you're on a system where "\n" just gets down (line feed) and you're missing the required carriage return.
That shouldn't be something you should care yourself: line.separator
property is adjusting to the host operating system so that it behaves like System.out.println
.
Upvotes: 6