【问题标题】:Scanner only reads file name and nothing else扫描仪只读取文件名,没有别的
【发布时间】:2013-11-19 17:31:12
【问题描述】:

我正在尝试实现一个基本的词法分析器。我现在卡在文件解析上。

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;
}

这是我的“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 ;
}

当我解析文件时,我得到:Error, token: p++.ppp on line: 1 is not valid 但 p++.ppp 是文件名!

此外,当我调试时,它会读取文件名,然后在 scanner.hasNextLine() 处退出。我错过了什么?

【问题讨论】:

    标签: java parsing java.util.scanner


    【解决方案1】:

    您误解了Scanner 的 API。来自Scanner(String) constructor 的文档:

    构造一个新的扫描器,生成从指定字符串扫描的值。

    参数:
    source - 要扫描的字符串

    这不是文件名 - 它只是一个字符串。

    您应该改用Scanner(File) 构造函数——或者更好的是,Scanner(File, String) 构造函数也可以指定编码。例如:

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

    (注意使用 try-with-resources 语句,以便扫描仪自动关闭。)

    【讨论】:

    • 是的,我承认只看了一眼扫描仪 api。我认为我什至没有查看构造函数。谢谢你。但是我确实得到了The constructor Scanner(File, Charset) is undefined
    • @Kalec:你使用的是什么版本的 Java?
    • 1.7.0_13运行环境搭建b20
    • @Kalec:你是对的 - 没有Charset 超载,很奇怪。不知道为什么我认为有。正在编辑...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 2018-03-18
    • 2013-12-04
    • 1970-01-01
    • 2012-07-21
    • 1970-01-01
    相关资源
    最近更新 更多