2016-04-22 135 views
0

我已經使用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; 
} 
} 
+0

嘗試發佈城市級 – Abdelhak

+0

構成@Abdelhak – user6216509

+0

我提供了城市類@Drew Kennedy – user6216509

回答

5

文件中的這些座標不是整數。我不希望nextInt做他們想要的。嘗試nextFloat

[編輯補充:]實際上,nextDouble可能是一個更好的主意。

+0

'nextFloat()'將小數點保持爲2嗎?真的很好奇。 :) –

+1

我不確定我是否理解你的問題。 Java中的「float」沒有任何與其關聯的特定小數位數。如果你調用'nextFloat',你會得到任何IEEE單精度浮點數最接近(比如說)16.47。實際上使用'nextDouble'而不是'nextFloat'可能是一個更好的主意 - 我只寫了'nextFloat',因爲我一直在看的最後一個SO問題是關於Python和Python調用它唯一的浮點類型'float' :-)。那麼你會得到最接近的「雙」到16.47。 –

+0

對不起,我的問題是'nextFloat'返回'16.47',或者它是否會填充更多的小數位,比如說'16.470000'。我並不熟悉Java的所有內部工作,因此對它很好奇。我同意'nextDouble'是更好的選擇。 :) –