我有一个对象Location,它接受参数String name,int xCoordinate,int yCoordinate。我有以下文本文件,从中读取值并将它们转换为Location对象。
Location: Italy 65 120
Location: Spain 20 100
Location: France 130 60
Location: England 160 140
Location: Scotland 65 100
Location: Hungary 110 120
Location: Ireland 20
120
Location: Russia 40 10
Location: America 90 15
Location: Greece
39 23
Location: India 49 5
Location: Japan 11 20
Location: Africa 110
100
Location: Norway 22 30
Location: Sweden 34 35
Location: Iceland
94 22
Location: Denmark 36 20
请注意,位置前面总是以"位置:"并且名称和坐标可以用任意数量的行分隔。
我已经提出了以下代码,但它似乎不起作用:
FileInputStream fileIn = new FileInputStream("src\\graph.txt");
Scanner scan = new Scanner(fileIn);
WorldMap map1= new WorldMap();
while(scan.hasNext()) {
if(scan.next().equals("Location:")) {
map1.addLocation(scan.next(), scan.nextInt(), scan.nextInt());
}
}
答案 0 :(得分:2)
用以下代码替换您的代码:
while(scan.hasNextLine()) {
if(scan.nextLine().startsWith("Location:")) {
//doWhatver you want to Do here
}
}
答案 1 :(得分:0)
最好是阅读所有行并使用一组正则表达式来确定如何处理该行。