gpt4 book ai didi

java - 在 Java 中读取文件并对其进行标记

转载 作者:行者123 更新时间:2023-12-02 09:56:36 25 4
gpt4 key购买 nike

我正在尝试弄清楚如何从文件中读取有关旅行推销员问题的一些数据。我已包含该文件的前几行(其余 13503 行的格式相同,因此我已删除它们)。该文件如下所示:

    NAME : usa12
COMMENT : Cities with population at least 500 in
TYPE : TSP
DIMENSION : 13509
EDGE_WEIGHT_TYPE : EUC_2D
NODE_COORD_SECTION
1 245552.778 817827.778
2 247133.333 810905.556
3 247205.556 810188.889
4 249238.889 806280.556
5 250111.111 805152.778
6 254475.000 804794.444

我对两件事感兴趣。维度值和城市坐标。显示了编号为 1,...,6 的城市(但总共有 13509 个),它们的 xy 坐标都是相邻的。例如。城市 4 有 x=249238.889y=806280.556。基本上我想读取我的文件并存储数据,如下所示:

int dimension = read dimension of 13509
Coordinate[] xy = create coordinates array, with coordinates of each city

其中坐标对象的定义如下:

public class Coordinate {
double x;
double y;
public Coordinate(double x, double y) {
this.x = x;
this.y = y;
}
}

我想我需要使用缓冲读取器、一些 IO 异常和字符串标记器。我对此很陌生,所以我不太确定如何实现它。我不知道如何具体读取尺寸值以及x和y坐标。有人有一些建议的实现吗?

最佳答案

这是一个基本示例。如有更改将更新。

import java.util.*;
import java.io.*;
class SO{
public static void main(String...a)throws Exception{
System.out.println("Start");


//Read thing
File f = new File("so_data.txt");

Scanner s = new Scanner(f);

int counts = 0;

s.nextLine();//skip 1
s.nextLine();//skip 2
s.nextLine();//skip 3
counts = Integer.parseInt(s.nextLine().split(" ")[2]);//use 4th
s.nextLine();//skip 5
s.nextLine();//skip 6
System.out.println(counts+" : counts");



counts = 6;//DUMMY DATA FOR TEST FILE - REMOVE FOR ACTUAL FILE

Coordinate[] xy = new Coordinate[counts];


int i = 0;

while(i<counts){ // picking exactly the required number of items.

String line = s.nextLine();
String[] vals = line.split(" ");

double x = Double.parseDouble(vals[1]);
double y = Double.parseDouble(vals[2]);

Coordinate c = new Coordinate(x,y);
// System.out.println(c);
xy[i++] = c;
}


for( i = 0;i<xy.length;i++)
System.out.println("for index "+i+") "+xy[i]);

}
}
class Coordinate {
double x;
double y;
public Coordinate(double x, double y) {
this.x = x;
this.y = y;
}
public String toString(){
return "Coord:: "+x+" , "+y;
}
}
<小时/>

so_data.txt

NAME : usa12
COMMENT : Cities with population at least 500 in
TYPE : TSP
DIMENSION : 13509
EDGE_WEIGHT_TYPE : EUC_2D
NODE_COORD_SECTION
1 245552.778 817827.778
2 247133.333 810905.556
3 247205.556 810188.889
4 249238.889 806280.556
5 250111.111 805152.778
6 254475.000 804794.444

关于java - 在 Java 中读取文件并对其进行标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55958540/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com