[英]Formatting data read in from text file
I have an object Location which takes parameters String name, int xCoordinate, int yCoordinate. 我有一个对象Location,该对象接受参数字符串名称,int xCoordinate,int yCoordinate。 I have the following text file from which to read in the values and turn them into Location objects.
我有以下文本文件,可从中读取值并将它们转换为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
Note that a Location is always preceded by "Location:" and that the name and coordinates can be seperated by any number of lines. 请注意,位置始终以“ Location:”开头,并且名称和坐标可以用任意数量的行分隔。
I have come up with the following code but it does not seem to be working: 我想出了以下代码,但似乎无法正常工作:
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());
}
}
Replace your code with this : 用以下代码替换您的代码:
while(scan.hasNextLine()) {
if(scan.nextLine().startsWith("Location:")) {
//doWhatver you want to Do here
}
}
更好的方法是读取所有行并使用一组正则表达式确定如何处理该行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.