gpt4 book ai didi

java - 如何将同一个文本文件中的整数和字符串添加到不同的数组中

转载 作者:行者123 更新时间:2023-12-02 02:20:40 25 4
gpt4 key购买 nike

我需要编写一个程序,将文本文件中的值存储到多个数组中。文本文件如下所示:

1995 年 6 月 987 65 艾里森

1995 年 7 月 973 85 艾琳

1995 年 8 月 929 120 菲利克斯

1995 年 8 月 968 95 温贝托

1995年8月965 95鸢尾

我需要将每一列添加到一个单独的数组中。如何告诉程序专门针对一列将其添加到数组中,然后是下一列?

我尝试这样做:

    File fileName = new File ("hurricanedata.txt");
Scanner inFile = new Scanner(fileName);


while (inFile.hasNextLine()) {
index++;
inFile.nextLine();
}

hurricaneNames = new String [index];
years = new int [index];
months = new String [index];
pressures = new int [index];
windSpeeds = new int [index];

while (inFile.hasNext()) {

int i = 0;
years [i] = inFile.nextInt();
months [i] = inFile.next();
pressures [i] = inFile.nextInt();
windSpeeds [i] = inFile.nextInt();
hurricaneNames [i] = inFile.next();
System.out.println(years[i]); //print statement to test
i++;
}

但是 print 语句没有打印任何内容。

最佳答案

执行此操作后:

while (inFile.hasNextLine()) {
index++;
inFile.nextLine(); // HERE
}

现在正在从文件末尾读取您的文件。因此 next() 不会像您希望的那样从文件的开头开始。

您只需使用扫描仪重新打开文件即可:

File fileName = new File ("hurricanedata.txt");
Scanner inFile = new Scanner(fileName);


while (inFile.hasNextLine()) {
index++;
inFile.nextLine(); // Increments the line of the file that you're reading, so the
// next "next()" you call starts at the >next< line of the file.
}
inFile.close();
inFile = new Scanner(fileName); // NOTE: Restarts the Scanner, ensuring that it
// starts reading from the beginning of the file again.

hurricaneNames = new String [index];
years = new int [index];
months = new String [index];
pressures = new int [index];
windSpeeds = new int [index];

int i = 0; // NOTE: This should be OUT of the loop, so that i increments
// and doesn't restart to 0.
while (inFile.hasNext()) {

years [i] = inFile.nextInt();
months [i] = inFile.next();
pressures [i] = inFile.nextInt();
windSpeeds [i] = inFile.nextInt();
hurricaneNames [i] = inFile.next();
System.out.println(years[i]); //print statement to test
i++;
}

关于java - 如何将同一个文本文件中的整数和字符串添加到不同的数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48547621/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com