How to skip an enter using scanner?

56 Views Asked by At

I've been using a scanner to read a text file but get this output.

[f,

,

, f,

,

, f,

,

, f,

,

, f]

The text file characters are all separated by enters.

I've tried using scanner.skip("\n");, but that throws the NoSuchElementException. How do I fix it? The loop:

File file = new File("src/crossword/squares/" + Crossword + ".txt");
ArrayList<String> values = new ArrayList<String>();
        Scanner scanner;
    while(scanner.hasNext())
            {
                scanner.skip("\n");
                scanner.useDelimiter("");
                String value = scanner.next();
                values.add(value);
            }
        } catch(FileNotFoundException e) {
        e.printStackTrace();
        
        }
1

There are 1 best solutions below

1
harsh Kanodiya On

The correct escape sequence for a newline character is "\n" (not "/n"), and you should use it within double quotes, not slashes.

Scanner scanner = new Scanner(new File("your_file.txt"));

while (scanner.hasNext()) {
String line = scanner.nextLine();
// Process the line here
}

scanner.close();

The hasNext() method is a method provided by the java.util.Scanner class. It is used to check if there is another token available for reading from the input source, which could be a file, a stream, or other sources