Reputation: 10199
EDIT: Sorry about not being clear where the extra new line happens
I have a for loop that reads from different arrays in order to make a long string to display. The format of the string should be like this
Question X
Your answer was: Y
Correct answer was: Z
Question XX
Your answer was: YY
Correct answer was: ZZ
....
However when the string is produced it starts off fine but it gets to have an extra space as shown in the pattern below
....
Question X
Your answer was: Y
Correct answer was: Z
Question XX
Your answer was: YY
Correct answer was: ZZ
Question XXX
Your answer was: YYY
Correct answer was: ZZZ
Question XXXX
Your answer was: YYYY
Correct answer was: ZZZ
Question XXXXX
Your answer was: YYYYY
Correct answer was: ZZZZZ
...
This is the code I have to produce this:
for(int x=1;x<11;x++){
if(x==10)
{
longResultsString+="Question " + x + " " + isCorrect[9] + "\nYour answer was: " + detailedResultsUserChoices[9] +" \nCorrect answer was: " + answerChoices[9][4];
}
else{
longResultsString+="Question " + x + " "+isCorrect[x-1] + "\nYour answer was: " + detailedResultsUserChoices[x-1] +" \nCorrect answer was: " + answerChoices[x-1][4] + "\n\n";
}
}
and I am wondering if anyone has any suggestions for what would cause this behavior
Upvotes: 0
Views: 5177
Reputation: 2593
StringBuilder sb = new StringBuilder();
for(int x = 0; x < 10; x++) {
sb.append("Question " + (x + 1) + " " + isCorrect[x] + "\nYour answer was: " + detailedResultsUserChoices[x] + "\nCorrect answer was: " + answerChoices[x][4]);
if (x != 9) {
sb.append("\n");
}
}
sb.toString(); // the string you want
This may not even fix your code (a concrete example in the question would be nice), but it might help with having good code practices:
Upvotes: 1
Reputation: 44854
The value within
detailedResultsUserChoices[x-1]
has an embedded CR char
Upvotes: 0
Reputation: 3640
for(int x=1;x<=11;x++){
if(x==11)
{
longResultsString+="Question " + x + " " + isCorrect[9] + "\nYour answer was: " + detailedResultsUserChoices[9] +" \nCorrect answer was: " + answerChoices[9][4];
}
else{
longResultsString+="Question " + x + " "+isCorrect[x-1] + "\nYour answer was: " + detailedResultsUserChoices[x-1] +" \nCorrect answer was: " + answerChoices[x-1][4] + "\n";
}
Remove the second \n (new line) escape character from the else statement and change you for loop condition so that the if condition will have a chance.
Upvotes: 0
Reputation:
You had an extra /n in your else statement.. Try this now. Your code is slightly different from the output there so its hard to tell
for(int x=1;x<11;x++){
if(x==11)
{
longResultsString+="Question " + x + " " + isCorrect[9] + "\nYour answer was: " + detailedResultsUserChoices[9] +" \nCorrect answer was: " + answerChoices[9][4];
}
else{
longResultsString+="Question " + x + " "+isCorrect[x-1] + "\nYour answer was: " + detailedResultsUserChoices[x-1] +" \nCorrect answer was: " + answerChoices[x-1][4] + "\n";
}
}
Upvotes: 0