通过 API,我获得了一个包含许多不同数据的数组。但我只需要最后一个元素。
变量 sb 中有数组。但我无法访问这样的元素:sb[0](例如)
如果我打印变量 sb ,它看起来像这样:
{"data":[[[1583596801195,279.52],[1583596814340,279.52],[1583596815535,279.44563849372383],[1583596816730,279.2060000000001],[1583596913525,279.2060000000001],[1583596914720,279.28824435146447],[1583596915915,279.52],[1583597211080,279.52],[1583597212275,279.52000000000004],[1583597213470,279.52],[1583597609015,279.52],[1583597610210,279.5199999999999],[1583597707005,279.5199999999999],[1583597708200,279.52000000000004],[1583597709395,279.52],[1583597806190,279.52],[1583597807385,279.52000000000004],[1583597993805,279.52000000000004]]]}
在本例中,我只需要最后一个元素 (279.52000000000004)。
我的代码如下所示:
URL url = new URL("the URL i get the data from");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
InputStream instream = con.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
instream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println(sb);
抱歉,我没有编程经验。但如果有人能帮助我,我真的很感激。
感谢您的帮助。
最佳答案
如果您只需要最后一个元素,则不应附加结果。
相反,替换之前存储的值。
String result = null;
String line = null;
try {
while ((line = reader.readLine()) != null) {
//sb.append(line + "\n");
result = line; // not appending, but replacing
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
instream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println(result);
关于java - 获取数组的最后一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60579786/