我正在尝试从以下格式的文本文件中解析信息:
WarningGeotask: 0, 1
第一个词是某个对象的关键字,要在其后的数字中给出的坐标位置创建。这是我的循环目前的样子:
// Open file and scan for a line
File f = new File("Simulation.Configuration");
Scanner s = new Scanner(f);
while (s.hasNextLine()) {
// Parse each line with a temporary scanner
String line = s.nextLine();
Scanner s2 = new Scanner(line);
// Get keywords from the file to match to variable names
String keyword = s2.next();
//...Multiple if statements searching for different keywords...
else if (keyword.equals("WarningGeotask:")) {
int xCoord = s2.nextInt();
int yCoord = s2.nextInt();
WarningGeotask warningGeotask = new WarningGeotask(xCoord, yCoord);
s2.close();
continue;
}
}
但是,这段代码不能正常工作。事实上,String xCoord = s2.nextInt()
会抛出一个错误。我可以执行 s2.next()
并打印出返回 1 的 s2.nextInt()
。但我不确定我在使用 Scanner 时做错了什么0 和 1 设置为两个不同的变量。感谢您的帮助!
编辑:字符串变量 xCoord 和 yCoord 应该是 int - 我的错。
最佳答案
问题是 Scanner#nextInt() 返回一个数值(准确地说:一个 int 类型的值),您尝试将其分配给一个 String 变量。
所以代替:
String xCoord = s2.nextInt();
String yCoord = s2.nextInt();
尝试:
int x = s2.nextInt();
int y = s2.nextInt();
关于java - 使用逗号分隔坐标的扫描仪 NextInt(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21622567/