I am trying store a list of cities in a class using two co-ordinates(x,y) in java
My class is as follows:
public class City {
int x;
int y;
// Constructs a city at chosen x, y location
public City(int x, int y){
this.x = x;
this.y = y;
}
}
I have made another class to store the cities in an ArrayList
:
public class TourManager {
// Holds our cities
private static ArrayList destinationCities = new ArrayList<City>();
// Adds a destination city
public static void addCity(City city) {
destinationCities.add(city);
}
}
My main class is as follows:
public class Final {
public static void main(String[] args) {
// Create and add our cities
City city = new City(60, 200);
TourManager.addCity(city);
City city2 = new City(180, 200);
TourManager.addCity(city2);
City city3 = new City(80, 180);
TourManager.addCity(city3);
}
}
Here, I have stored three cities in the ArrayList
inside the main function. But now I want to take the input from a file in the following format. I just want to take the co-ordinates ignoring all other lines.
NAME: sample.tsp
TYPE: TSP
COMMENT: Odyssey of Ulysses (Groetschel/Padberg)
DIMENSION: 3
EDGE_WEIGHT_TYPE: GEO
NODE_COORD_SECTION
1 60 200
2 180 200
3 80 180
I want to use the scanner class to take the input but getting confused in using it. i have made a partial code fragment to take input but it isn't working:
Scanner in = new Scanner(new File("sample.tsp"));
String line = "";
int n;
in.nextLine();
in.nextLine();
in.nextLine();
line = in.nextLine();
line = line.substring(11).trim();
n = Integer.parseInt(line);
in.nextLine();
in.nextLine();
But how will I take the coordinates using the City class object as I have done before from this file?
You need to skip the first few lines, which you don't need.
Then split the lines to get the various numbers. Index 0 contains the serial no., 1 and 2 contain the coordinates. Then parse them to int
. eg:
in.nextLine();// multiple times.
//...
String cs = in.nextLine(); // get the line
City city = new City(Integer.parseInt(cs.split(" ")[1]), Integer.parseInt(cs.split(" ")[2]));
TourManager.addCity(city);
String cs2 = in.nextLine();
City city2 = new City(Integer.parseInt(cs2.split(" ")[1]), Integer.parseInt(cs2.split(" ")[2]));
TourManager.addCity(city2);
String cs3 = in.nextLine();
City city3 = new City(Integer.parseInt(cs3.split(" ")[1]), Integer.parseInt(cs3.split(" ")[2]));
TourManager.addCity(city3);
Whenever you use in.nextLine()
, actually it takes the string that you entered. So try to assign it to some string variable. For example:
String s =in.nextLine();
Also, just using in.nextLine();
which you did in 2nd,3rd 4th,8th and 9th line is not needed.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.