编辑:很抱歉不清楚额外的新行发生在哪里
我有一个for循环,它从不同的数组中读取,以便显示一个长字符串。字符串的格式应该是这样的
Question X
Your answer was: Y
Correct answer was: Z
Question XX
Your answer was: YY
Correct answer was: ZZ
....
然而,当生成字符串时,它会很好地启动,但它会有一个额外的空间,如下图所示
....
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
...
这是我必须制作的代码:
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";
}
}
我想知道是否有人对导致此行为的原因有任何建议
答案 0 :(得分:1)
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
这甚至可能无法修复您的代码(问题中的具体示例会很好),但它可能有助于实现良好的代码实践:
答案 1 :(得分:0)
你的else语句中有一个额外的/ n ..现在试试这个。你的代码与那里的输出略有不同,所以很难分辨
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";
}
}
答案 2 :(得分:0)
中的值
detailedResultsUserChoices[x-1]
有嵌入式CR char
答案 3 :(得分:0)
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";
}
从else语句中删除第二个\ n(新行)转义字符并更改循环条件,以便if条件有机会。