【发布时间】:2019-08-21 15:29:38
【问题描述】:
我正在尝试将坐标从文件读取到数组中。
每个坐标都有一个 id、一个x-value 和一个y-value。
文件格式如下:id position.x position.y
示例:
292961234 1376.42 618.056
29535583 3525.73 530.522
256351971 836.003 3563.33
20992560 4179.74 3074.27
注意:共有 4 行,共包含 4 个坐标。
我创建了 Node 类,它的构造函数需要 (int id, double x, double y)。
这是 NodeList 类,它应该有一个保存节点的数组属性:
package .....;
import java.io.File;
import java.util.Iterator;
import java.util.Locale;
import java.util.Scanner;
public class NodeList implements Iterable<Node> {
private Node[] nodes = getNodes();
@Override
public Iterator<Node> iterator() {
return null;
}
public Node[] getNodes() {
Node[] result;
File f;
Scanner scanner;
try {
f = new File("nodes.txt");
Scanner s = new Scanner(f);
int ctr = 0;
while (s.hasNextLine()) {
ctr++;
s.nextLine();
}
result = new Node[ctr];
}
catch (Exception e) {
return null;
}
try {
scanner = new Scanner(f);
}
catch (Exception e) {
return null;
}
Locale.setDefault(new Locale("C"));
for(int i = 0; i < result.length; i++) {
int id = scanner.nextInt();
double x = scanner.nextDouble();
double y = scanner.nextDouble();
result[i] = new Node(id,x,y);
}
return result;
}
public static void main(String[] args) {
NodeList nl = new NodeList();
}
}
Node 类:
package ...;
public class Node {
private int id;
private double x;
private double y;
public Node(int id, double x, double y){
this.id = id;
this.x = x;
this.y = y;
}
public int getId(){
return id;
}
public double getX(){
return x;
}
public double getY(){
return y;
}
}
当调用包含所示代码的方法时,我得到以下信息 例外:
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextDouble(Scanner.java:2564)
at ......NodeList.getNodes(NodeList.java:40)
at ......NodeList.<init>(NodeList.java:9)
at ......NodeList.main(NodeList.java:47)
Process finished with exit code 1
指向包含节点的文件的链接:https://pastebin.com/zhzp3DTi
【问题讨论】:
-
什么是
scanner?您是否尝试使用Scanner对象来读取文件?此外,请尝试在双表达式中使用逗号而不是点。 -
欢迎来到 StackOverflow。在stackoverflow.com/a/2788114/509840 有一个仅读取整数的相关答案。你认为你可以修改你的代码来读取一个整数和一个双精度数吗?
-
@GauravMall 扫描器是一个从我的文件中读取的扫描器对象。我们的老师给了我们一个他们使用点的文件,所以我想我必须坚持下去。