扫描仪只读取文件名而不读取任何其他内容 [英] 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;
}
这是我的名字p ++。ppp
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 ;
}
当我解析文件时,我得到:错误,令牌:p ++。ppp在线:1无效
但是p ++。ppp是文件名!
When I parse the file, I get: Error, token: p++.ppp on line: 1 is not valid
but p++.ppp is the file name!
当我调试时,它也是读取文件名,然后在 scanner.hasNextLine()
它只是退出。我错过了什么?
Also when I debug, it reads the file name and then at scanner.hasNextLine()
it just exits. What am I missing ?
推荐答案
你误解了扫描仪的API
。来自 扫描程序(字符串)
构造函数:
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.
参数:
source - 要扫描的字符串
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.)
这篇关于扫描仪只读取文件名而不读取任何其他内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!