【问题标题】:Reading in multiple data types from a txt file Java从 txt 文件 Java 中读取多种数据类型
【发布时间】:2016-12-03 21:48:52
【问题描述】:

我知道简单地从 txt 文件中读取数据已经存在很多问题,但我收到的 txt 文件包含以下内容:

1980 Aug    945 100 Allen1983 Aug   962 100 Alicia1984 Sep  949 100 Diana

第一个数字是年、月、风压、风速(节)和飓风名称。这种模式适用于几百个条目,我必须将每个不同的数字放入自己的数组中(年 []、月 []、压力 [] 等......)

我尝试了许多不同的方法,但这是我最近尝试的一个示例:

import java.io.IOException;
import java.io.File;
import java.io.FileReader;
import java.io.PrintWriter;
import java.util.Scanner;
public class Hurricanes2 {
public static void main(String[] args) throws IOException { 
int i = 0;
    int token1 = 0;
    String token2 = "";

    int[] years = new int[1000]; //token 1
    String[] months = new String[1000]; //token 2
    String[] names = new String[1000];
    int[] pressure = new int[1000]; //token 1
    int[] windSpeed = new int[1000]; //token 1
    int[] category = new int[1000]; //token 1

    Scanner s = new Scanner (new FileReader("hurcdata2.txt"));

while (s.hasNext()) {
        if (s.hasNextInt()) {
            token1 = s.nextInt();
            if (token1 >= 1980) {
                years[i] = token1;
            }
            else if (token1 >= 1000) {
                pressure[i] = token1;
            }
            else {
                windSpeed[i] = token1;
            }
        }
        else if (s.hasNext()) {
            token2 = s.next();
            if (token2.equals("Jun") || token2.equals("Jul") || token2.equals("Aug") || token2.equals("Sep") || token2.equals("Oct") || token2.equals("Nov")) {
                months[i] = token2;
            }
            else {
                names[i] = token2;
            }
        }
        token1 = 0;
        token2 = "";
        i++;
        }

当我使用 for-each 循环打印任何数组时,所有值都是 0。除非我只打印第一个元素(例如 a[0]),否则它将显示正确的值。任何其他索引 > 0 的仍显示 0。 我知道它有很多问题,但此时我正在尝试一些奇怪的事情来让它发挥作用。我不是在寻找对这段代码的更正,而是对整体问题的解决方案。

【问题讨论】:

  • 您是否在调试器中单步执行了代码?
  • 我试过了,但没有错误。一旦我按下步骤,它就会运行整个代码
  • 没有“错误”并不意味着没有问题。显然存在问题,因为您正在发布问题。逐步检查每一行代码,检查变量的变化,等等。学习正确的调试技术与学习语言一样重要。 blog.codeunion.io/2014/09/03/teaching-novices-how-to-debug-code

标签: java arrays while-loop java.util.scanner token


【解决方案1】:

您可以尝试在空格处拆分单词,然后将其存储在Objects 的数组中。然后您可以使用instanceof 来比较类型,例如if(obj instanceof Integer)...

【讨论】:

    猜你喜欢
    • 2012-01-13
    • 2016-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-02
    • 1970-01-01
    • 2016-05-27
    相关资源
    最近更新 更多