I want to take input from a file using the scanner class in Java. I want to read two coordinates of different cities from the file and then store them in an ArrayList
of type City
objects.
The input file format is as follows:
NAME : att48
COMMENT : 48 capitals of the US (Padberg/Rinaldi)
TYPE : TSP
DIMENSION : 5
EDGE_WEIGHT_TYPE : ATT
NODE_COORD_SECTION
1 6734 1453
2 2233 10
3 5530 1424
4 401 841
5 3082 1644
My sample code fragment is as follows: TourManager
is a class containing an ArrayList
of City objects. I haven't shown it here. City class contains every details (x,y coordinates) of a city.
try
{
Scanner in = new Scanner(new File("att48.tsp"));
String line = "";
int n;
//three comment lines
in.nextLine();
in.nextLine();
in.nextLine();
//get n
line = in.nextLine();
line = line.substring(11).trim();
n = Integer.parseInt(line);
City[] city= new City[n];
for (int i = 0; i < n; i++) {
city[i].x=0;
city[i].y=0;
}
//two comment lines
in.nextLine();
in.nextLine();
for (int i = 0; i < n; i++)
{
in.nextInt();
city[i].x = in.nextInt();
city[i].y = in.nextInt();
TourManager.addCity(city[i]);
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
But I am getting a NullPointerException
in the line.
city[i].x = in.nextInt();
Although I have initialized it by 0 previously, the code throws the NullPointerException
.
For clarity, City 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;
}
}
Is there a problem in the code?
You are getting error because after doing :
City[] city= new City[n];
You have not allocated memory to individual city[i]
elements.
You have to do something like this, but for this you need to add a default constructor to your city class as you are assigning x and y afterwards:
for (i=0;i <n ;i++){
city[i]= new City();
}
Add the following constructor in your City
class:
public City(){
}
or I would suggest you to revise your City
class:
public class City {
private int x;
private int y;
// Constructs a city at chosen x, y location
public City(int x, int y) {
this.setX(x);
this.setY(y);
}
public City() {
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
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.