gpt4 book ai didi

java - 扫描仪只读取文件名,没有别的

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:47:44 26 4
gpt4 key购买 nike

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

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

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

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

最佳答案

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

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

Parameters:
source - A string to scan

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

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

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

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

关于java - 扫描仪只读取文件名,没有别的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19846640/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com