Scanner only reads file name and nothing else

梦想与她 提交于 2020-01-08 18:03:07

问题


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 ?


回答1:


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.)



来源:https://stackoverflow.com/questions/19846640/scanner-only-reads-file-name-and-nothing-else

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!