0

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(",");
        }



    }

}

1 Answer 1

1

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(",").

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.