使用扫描仪将txt文件读入数组

发布于 2024-12-10 17:26:30 字数 890 浏览 0 评论 0原文

我有一个文本文件,大致如下所示:

类型、距离、长度、其他

A、62、17、abc、

A、12、4、、

A、6、90、、

A、46、53、、

等。

所有内容均以逗号分隔,但有时会有空白的。我需要能够使用扫描仪(而不是缓冲读取器)将这些数据读入数组,并能够以某种方式解释空白,以及用逗号分隔。稍后我将需要能够使用每列中的数据进行计算。如何将这些数据放入数组中?

这是我到目前为止所拥有的:(java)

import java.util.Scanner;
import java.io.*;

public class RunnerAnalysis {

    public static void main(String[] args) throws IOException {

        Scanner keyboard = new Scanner(System.in);

        System.out.print("File: ");
        String filename = keyboard.nextLine();

        File file = new File(filename);
        Scanner inputFile = new Scanner(file);

        inputFile.nextLine();

        String line = inputFile.nextLine();

        while(inputFile.hasNext())
        {
        String[] array = line.split(",");
        }



    }

}

I have a text file that looks roughly like this:

type, distance, length, other,

A, 62, 17, abc,

A, 12, 4,,

A, 6, 90,,

A, 46, 53,,

etc.

Everything is separated by commas, but sometimes there is a blank. I need to be able to read this data into an array using a scanner (not bufferedreader) and be able to account for the blanks somehow, as well as split by commas. Later I will need to be able to calculate things with the data in each column. How do I get this data into the array?

This is what I have so far: (java)

import java.util.Scanner;
import java.io.*;

public class RunnerAnalysis {

    public static void main(String[] args) throws IOException {

        Scanner keyboard = new Scanner(System.in);

        System.out.print("File: ");
        String filename = keyboard.nextLine();

        File file = new File(filename);
        Scanner inputFile = new Scanner(file);

        inputFile.nextLine();

        String line = inputFile.nextLine();

        while(inputFile.hasNext())
        {
        String[] array = line.split(",");
        }



    }

}

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

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

发布评论

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

评论(1

美人骨 2024-12-17 17:26:30

如果您确实想使用扫描仪(恕我直言,这不是一个好主意),您可以将分隔符设置为 ,

Scanner inputFile = new Scanner(...);
inputFile.useDelimiter(",");

while (inputFile.hasNext())
{
    String type = inputFile.next();
    int distance = inputFile.nextInt();
    int length = inputFile.nextInt();
    String other = inputFile.next();

    // Process...
}

我更喜欢将 BufferedReaderString.split(",") 结合使用。

If you really want to use a Scanner, which is IMHO not such a good idea, you can set the delimiter to ,.

Scanner inputFile = new Scanner(...);
inputFile.useDelimiter(",");

while (inputFile.hasNext())
{
    String type = inputFile.next();
    int distance = inputFile.nextInt();
    int length = inputFile.nextInt();
    String other = inputFile.next();

    // Process...
}

I prefer using a BufferedReader in combination with String.split(",").

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文