2013-11-23 55 views
0

我有一個圖的鄰接矩陣的file.how這個鄰接MATIX存儲在一個二維矩陣 我輸入文件看起來像如何存儲文件項,鄰接表

e 1 36 
e 2 45 
e 3 74 
e 4 18 
e 5 36 
e 6 74 
e 6 45 
e 6 136 
e 6 36 
e 6 21 
e 6 18 
e 7 18 
e 7 116 
e 7 74 
e 7 99 
e 7 81 
e 7 135 

我需要一個輸出作爲鄰接表:

1-->36 
2-->45 
3-->74 
4-->18 
5-->36 
6-->74-->45-->136-->36-->21-->18 
7-->18-->116--->74-->99-->81-->135 


import java.util.Scanner; 
import java.io.File; 
import java.io.FileNotFoundException; 
import java.util.StringTokenizer; 

public class Graph1 { 
    public static void main(String[] args) throws FileNotFoundException { 
     int linecount = 0, ec = 0; 
     String nbin = null, cbin = null; 
     int[][] data = null; 
     String e = "e"; 
     System.out.println("Graph Coloring Algorithm Test\n"); 
     Scanner sc = new Scanner(System.in); 
     System.out.print("Enter graph input file name: "); 
     String newfile = sc.nextLine() + ".txt"; 
     File file = new File(newfile); 
     Scanner scan = new Scanner(file); 
     while ((scan.hasNext())) { 
      StringTokenizer t = new StringTokenizer(scan.nextLine()); 
      if (t.nextToken().equals(e)) { 
       ec++; 
       nbin = scan.nextInt(); 
       cbin = scan.nextInt(); 
      } 
      linecount++; 

      for (int i = 0; i < 5; ++i) 
       for (int j = 0; j < 5; ++j) { 
        { 
         data[nbin][cbin] = 1; 
        } 
       } 
     } 
     for (int i = 0; i < 5; ++i) 
      for (int j = 0; j < 5; ++j) { 
       { 
        System.out.print(data[i][j]); 
       } 
      } 
    } 
} 

這代碼有錯誤。如何將字符串標記轉換爲整數 我該如何接受文件中以e開頭的行並將其添加到鄰接列表中。

+0

告訴我們你試過的東西。 – Linus

+0

如何分離以e開頭的數據條目? –

+1

您嘗試過的任何內容對我們來說都是有用的,可以給您一個答案。 – Linus

回答

0

在你的代碼中的第19行,你不應該使用scan.nextLine(),而應該使用scan.next(),因爲它是一個你正在使用的迭代器。

而且在第22,23行,您使用scan.nextInt()並嘗試將其上傳到字符串。除非你希望用戶輸入一個整數,你應該用你的19行指定的字符串相同我假設你的意思是「E」後的整數,所以你需要做這個:

StringTokenizer t = new StringTokenizer(scan.next()); 
      if (t.nextToken().equals(e)) { 
       ec++; 
       nbin = Integer.valueOf(t.nextToken()); 
       cbin = Integer.valueOf(t.nextToken()); 
      } 

你會需要將nbin & cbin更改爲整數才能使其工作。而你的二維數組始終爲空。您需要添加int[][] data = new int[Your First Size][Your Second Size];

而您的計算鄰接列表的邏輯將不起作用,因爲根據您的「矩陣輸入文件」,整數大於0-5。相反,我建議你應該使用Maps.

好吧,這會讓你更接近你的目標,但你需要自己做,以便理解和學習一些東西,所以我會留下你。

另請參閱: Java Docummentations

+0

我想實現使用鄰接list.this圖是一個代碼鄰接matrix.thnks澄清雖然雖然有一些錯誤我得到了正確的鄰接矩陣 –