Home > other >  How do I verify if the next token in a Scanner class is empty in order to differentiate between loop
How do I verify if the next token in a Scanner class is empty in order to differentiate between loop

Time:10-06

I am attempting to solve a problem given to us by our professor. I need to sort through a file, data.txt, by appending occurrences of ; with a blank space and occurrences of ;; with a new line. I am having an issue determining the syntax of the else if clause in the while loop.

Data.txt contains the following 2 lines:

john;88;CARL;;JAFF
HELEN;MARY;;123;99

The current code is as follows:

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

class Delimit {
    public static void main(String[] args) throws IOException {
        // Initiates new FileInputStream to read text document
        File f = new File("data.txt");
        // Initiates new Scanner to parse the file, and delimit at ";"
        Scanner s = new Scanner(f).useDelimiter(";");

        // Parses through each token
        while (s.hasNext()) {
            // 
            if (s.hasNext()) {
                // Prints next token followed by a space
                System.out.print(s.next()   " ");
            }
            // else if (next token is empty) {
                // Prints next token followed by a new line
                System.out.print(s.next()   "\n");
            }
        }
        s.close(); // Closes the Scanner
    }
}

If there is a better approach to the delimiting and replacing methods, please enlighten me! I have been trying to improve my grasp on regex and the delimitation of strings. Thanks!

CodePudding user response:

Personally I would do away with using delimiters and just do a simple replace, ;; -> \n then ; -> ;

 Scanner s = new Scanner(f);
 String line = s.nextLine ();
 while (line != null) {
    s.o.p (line.replace(";;", "\n").replace(";", "; "));
    line = s.nextLine ();
}

CodePudding user response:

public static void main(String... args) throws FileNotFoundException {
    try (Scanner scan = new Scanner(new File("data.txt"))) {
        scan.useDelimiter("[;\r]"); // \r as line separator in the file under Windows
        boolean addSpace = false;

        while (scan.hasNext()) {
            String str = scan.next().trim();

            if (str.isEmpty()) {
                System.out.println();
                addSpace = false;
            } else {
                if (addSpace)
                    System.out.print(' ');

                addSpace = true;
                System.out.print(str);
            }
        }
    }
}
  • Related