Parsing a text file string by string in java

So I’m having a problem with parsing a text file. Let’s say I have a text file with contents like this(all strings are separated by a space and all lines after line 1 only contain 2 strings):

a b c d e
a b
c d

I need to process the first line one string at a time. That is “a”(then use a for a method) then “b”(use b for a method) and so on.

After this, I need to process lines 2 and 3 in a different way. Read line 2, store “a” in a variable as e1, then process “b” and store b in a variable e2. Then I need to use e1 and e2 for a separate method. All lines after line 1 do the same thing as I just described.

My problem is that my code is just reading the whole line and storing that as the variables. Thus, I’m not reading each individual string. Also, I don’t understand how to tell when I’m done processing line 1(this is important because I use a different method for all lines after line 1). Here’s what I have:

Scanner scan = new Scanner(new File(args[0]));
        while(scan.hasNext()){
        String input = scan.nextLine();
        t.addV(input);
        }

        while(scan.hasNext()){
            String e1 = scan.next();
            String e2 = scan.next();
            t.addE(e1, e2);
        }

I know this is very wrong but I’m just looking to understand how I would know when I’m done reading line 1 and how I would just read each individual string.

Answer

You are really close, just a couple things off.

Step 1: getting the first line and calling a method for each individual letter

String firstLine = scan.nextLine();

// splits the line into a letter array
String[] letters = firstLine.split("\s");

for(String letter: letters){
    // do your method
}

Step 2: Getting the two individual letters and calling methods depending on the letter:

while(scan.hasNextLine()){
    String line = scan.nextLine();
    String[] lets = line.split("\s");

    String e1 = lets[0];
    String e2 = lets[1];

    // do your methods with the individual letters
}

You could of course use scan.next() to retrieve one letter at a time, but it seems by the way you worded your question that the line that the letters are on is needed knowledge to the method call. Which is why I’ve also assumed that there are a maximum of two letters per line on subsequent lines.

Leave a Reply

Your email address will not be published. Required fields are marked *