我已經使用scanner類從給定的文本文件獲取輸入。文件格式如下:從java中的文件獲取輸入時獲取異常
NAME: burma14
TYPE: TSP
COMMENT: 14-Staedte in Burma (Zaw Win)
DIMENSION: 5
EDGE_WEIGHT_TYPE: GEO
NODE_COORD_SECTION
1 16.47 96.10
2 16.47 94.44
3 20.09 92.54
4 22.39 93.37
5 25.23 97.24
我的示例代碼片段如下:
public static void main(String[] args) {
try
{
Scanner in = new Scanner(new File("burma14.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]= new City();
}
//System.out.println("" +n);
//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();
}
}
基本上我在這裏做的是採取從線路DIMENTION值,並根據這一點,我已經存儲了x和y協調不同的城市到不同的城市對象。
但我得到以下異常:
java.util.InputMismatchException
在該行:
city[i].x = in.nextInt();
我需要做任何改變?
市級如下:
public class City {
int x;
int y;
// Constructs a randomly placed city
public City(){
}
// Constructs a city at chosen x, y location
public City(int x, int y){
this.x = x;
this.y = y;
}
// Gets city's x coordinate
public int getX(){
return this.x;
}
// Gets city's y coordinate
public int getY(){
return this.y;
}
}
嘗試發佈城市級 – Abdelhak
構成@Abdelhak – user6216509
我提供了城市類@Drew Kennedy – user6216509