[英]Error in taking input from file using scanner class in java
我想使用Java中的掃描器類從文件中獲取輸入。 我想從文件中讀取不同城市的兩個坐標,然后將它們存儲在City
對象類型的ArrayList
中。
輸入文件格式如下:
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
我的示例代碼片段如下: TourManager
是一個包含City對象的ArrayList
的類。 我沒有在這里顯示。 城市類別包含城市的每個詳細信息(x,y坐標)。
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();
}
但是我在行中得到了NullPointerException
。
city[i].x = in.nextInt();
盡管我之前已將其初始化為0,但是代碼拋出NullPointerException
。
為了清楚起見,城市等級如下:
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;
}
}
代碼中有問題嗎?
您收到錯誤是因為這樣做之后:
City[] city= new City[n];
您尚未為單個city[i]
元素分配內存。
您必須執行類似的操作,但是為此您需要在城市類中添加默認構造函數,因為隨后要分配x和y:
for (i=0;i <n ;i++){
city[i]= new City();
}
在您的City
類中添加以下構造函數:
public City(){
}
或者我建議您修改您的City
班級:
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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.