简体   繁体   English

在for循环中如何将数据写入字符串

[英]How to write data to a String when in a for-loop

So basically I have this database that is a for loop. 所以基本上我有一个for循环的数据库。 It gives a different score every time, which I need to save to a String (or file, but I guess a string would be easier, because I need it to be empty at every new call for the database). 每次都会给出不同的分数,我需要将其保存到String(或文件,但是我想字符串会更容易,因为在每次数据库调用时都需要将其为空)。

I want to store all the scores by going through the loop, and then adding a , after each score (to keep them seperate) but my code isn't working because a part of the code is outside the for loop. 我想通过循环来存储所有分数,然后在每个分数之后添加一个(以使其分开),但是我的代码不起作用,因为一部分代码在for循环之外。 How do I fix this? 我该如何解决? Or are there better/other methods to do what I want to create? 还是有更好/其他的方法来做我想创建的?

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();

Try this: 尝试这个:

StringBuilder sb = new StringBuilder();
for (Database contact : contacts) { 
    if(sb.length > 0) {
        sb.append(", ");
    }
    sb.append(contact.getMP());
}
...
sb.toString();

Try this 尝试这个

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();

Hope this helps and enjoy your work 希望这对您有所帮助,并祝您工作愉快

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM