-1 java arrays java.util.scanner
我使用了scanner类来从给定的文本文件中获取输入.文件格式如下:
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
Run Code Online (Sandbox Code Playgroud)
我的示例代码片段如下:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
基本上我在这里所做的就是从DIMENTION行中获取值,并根据这一点,我将不同城市的x和y坐标存储到不同的城市对象中.
但我得到以下异常:
java.util.InputMismatchException
Run Code Online (Sandbox Code Playgroud)
在线:
city[i].x = in.nextInt();
Run Code Online (Sandbox Code Playgroud)
我需要做出任何改变吗?
城市课程如下:
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;
}
}
Run Code Online (Sandbox Code Playgroud)