如何在java中for循环的Array out侧存储循环字符串数据?

时间:2018-01-15 12:07:09

标签: java arrays json mongodb for-loop

Customer dtls = new Customer();
String missing = dtls.getList(stingName, intAge, intMob, stingDOB);
JSONArray mJsonArray_miss_dtls = new JSONArray(missing);
String miss = "";
for (int k = 0; k < mJsonArray_miss_dtls.length(); k++) {
    JSONObject missingObject = mJsonArray_miss_dtls.getJSONObject(k);
    String s1 = missingObject.getString("DOB");
    String[] b = s1.split("T");
    String[] b1 = b[0].split("-");
    miss = b1[0] + "/" + b1[1];
    cnt++;
}

这里我想将“miss(string)”数据存储到for循环之外的一个数组中,我可以将这个for循环的所有数据存储在一个数组中。

1 个答案:

答案 0 :(得分:0)

你需要在循环内声明miss变量,在循环外声明结果Array,然后当你在循环中时,将miss变量添加到res数组中。

Customer dtls = new Customer();
String missing = dtls.getList(stingName, intAge, intMob, stingDOB);
JSONArray mJsonArray_miss_dtls = new JSONArray(missing);
Integer length = mJsonArray_miss_dtls.length();
String[] res= new String[lenght];
for (int k = 0; k < lenght; k++) {
    String miss = "";
    JSONObject missingObject = mJsonArray_miss_dtls.getJSONObject(k);
    String s1 = missingObject.getString("DOB");
    String[] b = s1.split("T");
    String[] b1 = b[0].split("-");
    miss = b1[0] + "/" + b1[1];
    res[k]=miss;
    cnt++;
}

更紧凑的解决方案:

Customer dtls = new Customer();
String missing = dtls.getList(stingName, intAge, intMob, stingDOB);
JSONArray mJsonArray_miss_dtls = new JSONArray(missing);
Integer length = mJsonArray_miss_dtls.length();
String[] res= new String[lenght];
for (int k = 0; k < lenght; k++) {
    JSONObject missingObject = mJsonArray_miss_dtls.getJSONObject(k);
    String s1 = missingObject.getString("DOB");
    String[] b = s1.split("T");
    String[] b1 = b[0].split("-");
    res[k]=b1[0] + "/" + b1[1];
    cnt++;
}