1

所以基本上我有这个数据库,它是一个 for 循环。它每次都会给出不同的分数,我需要将其保存到字符串(或文件,但我想字符串会更容易,因为我需要在每次新调用数据库时它为空)。

我想通过循环存储所有分数,然后在每个分数之后添加一个 , (以保持它们分开),但我的代码不起作用,因为部分代码在 for 循环之外。我该如何解决?还是有更好的/其他方法来做我想要创建的?

DatabaseHandler db = new DatabaseHandler(camera.this);
List<Database> contacts = db.getAllContacts();
for (Database contact : contacts) {
    String test = contact.getMP();
    StringWriter stringWriter = new StringWriter();
    PrintWriter printWriter = new PrintWriter(stringWriter);
    printWriter.println(test);
}  
printWriter.flush();
printWriter.close();
return stringWriter.toString();
4

2 回答 2

4

尝试这个:

StringBuilder sb = new StringBuilder();
for (Database contact : contacts) { 
    if(sb.length > 0) {
        sb.append(", ");
    }
    sb.append(contact.getMP());
}
...
sb.toString();
于 2013-05-19T21:59:35.310 回答
1

尝试这个

DatabaseHandler db = new DatabaseHandler(camera.this);
List<Database> contacts = db.getAllContacts();
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
boolean first = true;
for (Database contact : contacts) {
   if(!first) printWriter.print(", ");
   else first = false;
   String test = contact.getMP();
   printWriter.print(test);      
}      
printWriter.flush();
printWriter.close();
return stringWriter.toString();

希望这对您有所帮助并享受您的工作

于 2013-05-19T21:47:27.763 回答