2016-03-16 118 views
0

所以我試圖建立一個圖並找到兩個對象之間的最短路徑。爲了建立圖我讀名稱和值從輸入文件:Java - 從文件讀取值?

Location1 0 0 0 
Location2 5 0 0 
Location3 5 5 0 
Location4 0 5 0 

我的問題是我怎麼在這些值讀?下面是我在做什麼我的主要方法:

public static void main(String[] args) { 
     // You can test your program with something like this. 
     In in = new In(args[0]); 
     int T = in.readInt(); 
     for (int t=1; t<=T; t++) { 
     System.out.println("Case " + t + ":") ; 
     Edge w = new Edge(in); 
     } 
    } 

然後在那裏我找到每個位置的座標的另一種方法,存儲在哈希表中的每個點,然後移動到下一行:

public In coordinates(in){ 
    while (in.hasNext()){ 
     String location = in.next(); 
     String point1 = args[1]; 
     String point2 = args[2]; 
     String point3 = args[3]; 
    } 
} 

我不明白的是我如何將這些值添加到一個表,然後總是將這些位置與這些座標關聯。我想找到用弗洛伊德的最短路徑 - 沃肖爾的算法,我可以這樣做:

for (int k = 0; k < n; k++) { 
    for (int i = 0; i < n; i++) { 
     for (int j = 0; j < n; j++) { 
      dist[i][j] = Math.min(dist[i][j], dist[i][k] + dist[k][j]); 
     } 
    } 
} 

我想這些值進入一個二維數組名爲DIST,但我不知道如何將這些值賦給陣列。

回答

0

你可以用一個BufferedReader和文件閱讀器

File file = new File(replace with file location); 
FileReader fr = new FileReader(file); 
BufferedReader br = new BufferedReader(fr); 
while ((line = br.readLine()) != null) { 
    //process line will be in the format of a String 
} 
br.close(); 

線將等於什麼文件中的當前行是做到這一點。它會繼續讀文件直到文件結束爲止

0

我建議你做一個自定義對象,如Location,然後用HashMap來保留鏈接信息。

一旦你閱讀完整的輸入並準備HashMap你可以迭代它並做你的計算。

請參見下面的代碼片段:

位置類:

public class Location 
{ 
    private String location; 
    private int point1; 
    private int point2; 
    private int point3; 

    public Location(String location, int point1, int point2, int point3) { 
     this.location = location; 
     this.point1 = point1; 
     this.point2 = point2; 
     this.point3 = point3; 
    } 

    public void setLocation(String location) { 
     this.location= location; 
    } 

    public String getLocation() { 
     return this.location; 
    } 

    public void setPoint1(int point1) { 
     this.point1 = point1; 
    } 

    public int getPoint1() { 
     return this.point1; 
    } 

    public void setPoint2(int point2) { 
     this.point2 = point2; 
    } 

    public int getPoint2() { 
     return this.point2; 
    } 

    public void setPoint3(int point3) { 
     this.point3 = point3; 
    } 

    public int getPoint3() { 
     return this.point3; 
    } 
} 

主類:

public class Foo 
{ 
    public static void main (String[] args) 
    { 
     Foo f = new Foo(); 
     f.run(); 
    } 

    private void run() { 
     Map<String,Location> locationMap = new HashMap<>(); 
     Scanner in = new Scanner(System.in); 
     String line = null; 
     while(in.hasNext()) { 
      line = in.nextLine(); 
      String[] split = line.split(" "); 
      locationMap.put(split[0],new Location(split[0],Integer.parseInt(split[1]), 
          Integer.parseInt(split[2]),Integer.parseInt(split[3]))); 
     } 

     /* Iterate locationMap and do your calculations */ 
    } 
} 

在這裏,我已經使用System.in讀取從控制檯輸入。您可以將其替換爲從任何所需文件獲取輸入。