用于循环添加新行

时间:2014-08-07 00:41:43

标签: java for-loop

编辑:很抱歉不清楚额外的新行发生在哪里

我有一个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";

      }
 }

我想知道是否有人对导致此行为的原因有任何建议

4 个答案:

答案 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

这甚至可能无法修复您的代码(问题中的具体示例会很好),但它可能有助于实现良好的代码实践:

  • 0 index loops
  • 在循环中构建像这样的长字符串时使用StringBuilder
  • DRY(不要重复自己) - 你最后只想减少换行,对吧?然后无需复制else部分中所有其余的公共语句。

答案 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条件有机会。