简体   繁体   中英

Scanner only reads file name and nothing else

I'm trying to implement a rudimentary lexer. I'm stuck on the file parsing at the moment.

public ArrayList<Token> ParseFile () {

    int lineIndex = 0;
    Scanner scanner = new Scanner(this.fileName);

    while (scanner.hasNextLine()) {

        lineIndex++;
        String line = scanner.nextLine();

        if (line.equals(""))
        continue;

        String[] split = line.split("\\s"); 
        for (String s : split) {
        if (s.equals("") || s.equals("\\s*") || s.equals("\t"))
        continue;
        Token token = new Token(s, lineIndex);
        parsedFile.add(token);

        }
    }
    scanner.close();
    return this.parsedFile;
}

This is my fille called "p++.ppp"

#include<iostream>

using namespace std ;

int a ;
int b ;

int main ( ) {

    cin >> a ;
    cin >> b ;

    while ( a != b ) {
        if ( a > b )
            a = a - b ;
        if ( b > a )
            b = b - a ;
    }

    cout << b ;

    return 0 ;
}

When I parse the file, I get: Error, token: p++.ppp on line: 1 is not valid but p++.ppp is the file name!

Also when I debug, it reads the file name and then at scanner.hasNextLine() it just exits. What am I missing ?

You've misunderstood the API for Scanner . From the docs for the Scanner(String) constructor :

Constructs a new Scanner that produces values scanned from the specified string.

Parameters:
source - A string to scan

It's not a filename - it's just a string.

You should use the Scanner(File) constructor instead - or better yet, the Scanner(File, String) constructor to specify the encoding as well. For example:

try (Scanner scanner = new Scanner(new File(this.fileName), "UTF_8")) {
    ...
}

(Note the use of a try-with-resources statement so the scanner gets closed automatically.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM