Java 如何从文本文件的字符串中提取双精度值

发布于 2024-12-28 16:34:45 字数 747 浏览 0 评论 0原文

我的 Java 任务是编写一个 Java 应用程序,该应用程序使用包含地震信息的文本文件中的数据,并生成包含以下内容的报告:

读取值的数量,

震级的总和,

平均震级值(精确到小数点后两位),

最大震级值、发生地点和时间

最小震级值、发生地点和时间

可以获得使用 File 和 Scanner 类打开的文件,但我无法让它读取仅提取双精度值(即以下幅度:1.6、1.8 等)。我可以让它计算行数。我尝试过使用 Scanner 和 Pattern 类来分隔符,然后使用 Double parse,但它不起作用。我肯定是一个菜鸟,而这门课刚刚迈出了一大步。

从文本文件输入的示例:

1.6,"Southern California","Wednesday, January 18, 2012 19:19:12 UTC"
1.8,"Southern California","Wednesday, January 18, 2012 19:03:00 UTC"
1.8,"Southern California","Wednesday, January 18, 2012 18:46:53 UTC"
4.7,"Bonin Islands, Japan region","Wednesday, January 18, 2012 18:20:40 UTC"
1.6,"Southern California","Wednesday, January 18, 2012 17:58:07 UTC"

My Java assignment is to to write a Java application that uses data from a text file with earth quake information and generate a report with:

the count of the number of values read,

the total sum of the magnitudes,

the average magnitude value (to 2 decimal places),

the maximum magnitude value, where it happened and when

the minimum magnitude value, where it happened and when

I can get the file to open using File and Scanner classes but I can't get it to read extract only a double (i.e the magnitudes below: 1.6, 1.8, ect.). I can get it to count the number of lines. I've tried deliminators with the Scanner and Pattern classes and then using Double parse but it won;t work. I'm a rookie for sure and this class just took a leap.

Example of input from text file:

1.6,"Southern California","Wednesday, January 18, 2012 19:19:12 UTC"
1.8,"Southern California","Wednesday, January 18, 2012 19:03:00 UTC"
1.8,"Southern California","Wednesday, January 18, 2012 18:46:53 UTC"
4.7,"Bonin Islands, Japan region","Wednesday, January 18, 2012 18:20:40 UTC"
1.6,"Southern California","Wednesday, January 18, 2012 17:58:07 UTC"

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

掀纱窥君容 2025-01-04 16:34:45

试试这个

String str = "1.6,california,wednesday,whatever";
String[] results = str.split(",");
Double testDouble = Double.valueOf(str[0]);

Try this

String str = "1.6,california,wednesday,whatever";
String[] results = str.split(",");
Double testDouble = Double.valueOf(str[0]);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文