java - 获取数组的最后一个元素

标签 java database postman

通过 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/

相关文章:

java - 如何在Java中创建字符和动态ArrayList的映射

mysql - 在 mysql 上使用 Limit random

mysql - 将数据复制到另一个表以及链接表中以维护关系

ssl - 在 curl -k 中请求工作,但不在 Postman 中禁用 SSL

asp.net - 发布 postman key 斗篷

postman - postman 响应测试中的 OR 运算符

java - Intellij 想法 : How do I create custom Inspection rule with regexp

java - Firebase 快照监听器 : Glide Illegal Argument Exception on Activity Destroyed (Java)

java - 如果 swing 在 Jpanel 中调用 validate(),JComponent 会更改框架的位置

python - 仅当条目不存在时才将条目添加到数据库的正确方法;使用 python + peewee