【问题标题】:JAVA: How can I read a text file and store the data into an array if I know how many numbers are in the text file? [closed]JAVA:如果我知道文本文件中有多少个数字,如何读取文本文件并将数据存储到数组中? [关闭]
【发布时间】:2015-02-15 21:30:01
【问题描述】:

我有一个如下所示的文本文件:

14(*这是后面的数字的行数)
1
2
3
4
5
6
7
8
9
10
11
12
13
14

现在我需要使用 for 循环使用 Scanner 读取这些数据,然后将数字(第一行除外)存储在一个数组中。

到目前为止我有这个,但我卡住了:

import java.io.*;
import java.util.*;
public class DirectoryLookupApplication {
   public static void main(String[] args) throws IOException {

   Scanner dataFile = new Scanner(new File("Data3.txt"));
   int numTimes = dataFile.nextInt(); //since the first line tells us how many numbers are in the file-how many times loop will run
   int dataText = new int [numTimes];   
 }
}

【问题讨论】:

  • 文本文件由一个新行分隔 - 所以每个数字都在自己的行上。

标签: java arrays file text


【解决方案1】:

所以您需要一个执行 14 次读取的 for 循环,如下所示:

for (i = 0; i < numTimes; i++)
{
    dataText[i] = dataFile.nextInt();
}

【讨论】:

  • 批准了编辑,但是对于 OP 这意味着如果你想像这样使用它,你需要将 dataText 设置为一个数组。就像: int[] dataText = new int[numTimes]
【解决方案2】:

这是昨天的一个类似问题(我的答案中的代码已经过测试是否有效..)您可以根据需要对其进行转换。

Store 2D array (String) to file and retrieve it

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-26
    • 1970-01-01
    • 2021-07-10
    相关资源
    最近更新 更多