2013-10-22 117 views
0

我從文件讀取有大問題。我的在文件中的數據看起來像Tokenizer讀取其他變量

8 
2 4 5 6 
1 3 4 8 
2 8 
1 2 6 8 
1 6 
1 4 5 7 8 
6 8 
2 3 4 6 7 

我想讀8到變量n(n表示2D表尺寸:A [N] [N])和休息值表。我寫這篇文章,但代碼工作很好,當我從文件中刪除第一行(值8)和申報表的大小自己

import java.io.*; 
import java.util.StringTokenizer; 
class dfs 
{ 
private static PrintWriter zapis; 
static void przeszukiwanie_w_glab(int a[][], int m[], int i, int n) 
{ 
    int j; 
    System.out.println("\t" + (i+1)); 
    zapis.print((i+1)); 
    m[i] = 1; 
    for(j=0; j<n; j++) 
     if(a[i][j]==1 && m[j]==0) 
      przeszukiwanie_w_glab(a,m,j,n); 
} 
public static void main(String args[]) throws IOException 
    { 
     zapis = new PrintWriter("Out0204.txt"); 
     int n=8,i; 
     int m[]= new int[n]; 
     int a[][] = new int[n][n]; 
     for (i=0; i<n; i++) 
     { 
      m[i] = 0; 
     } 

     BufferedReader in = new BufferedReader(new FileReader("In0204.txt")); 
     String line; 
     for (int curLine = 0; (line = in.readLine()) != null; curLine ++) { 
      StringTokenizer tok = new StringTokenizer(line); 
      while (tok.hasMoreElements()) 
       a[curLine][Integer.parseInt(tok.nextToken()) - 1] = 1; 
     } 
     in.close(); 
     System.out.println("\nKolejnosc odwiedzanych wierzcholkow : \n"); 
     for (i=0; i<n; i++) 
      if (m[i]==0) 
      { 
       przeszukiwanie_w_glab(a,m,i,n); 
      } 
     zapis.close();   
    } 

}

回答

0

不這項工作?:

public static void main(String args[]) throws IOException 
{ 

    BufferedReader in = new BufferedReader(new FileReader("In0204.txt")); 
    int n = Integer.parseInt(in.readLine()); 

    zapis = new PrintWriter("Out0204.txt"); 
    int i; 
    int m[]= new int[n]; 
    int a[][] = new int[n][n]; 
    for (i=0; i<n; i++) 
    { 
     m[i] = 0; 
    } 


    String line; 
    for (int curLine = 0; (line = in.readLine()) != null; curLine ++) { 
     StringTokenizer tok = new StringTokenizer(line); 
     while (tok.hasMoreElements()) 
      a[curLine][Integer.parseInt(tok.nextToken()) - 1] = 1; 
    } 
    in.close(); 
    System.out.println("\nKolejnosc odwiedzanych wierzcholkow : \n"); 
    for (i=0; i<n; i++) 
     if (m[i]==0) 
     { 
      przeszukiwanie_w_glab(a,m,i,n); 
     } 
    zapis.close(); 
} 

更重要的是,編碼時請遵守Java命名約定。

+0

此代碼工作,但我想從文件中讀取值8(變量n),然後實現表a [n] [n]。所以我不知道如何從文件讀取第一行到變量n,並像在我的實際代碼中一樣休息到表格。 – Damian

+0

只要做到這一點:讀取第一行,將其存儲在n中,分配您的數組,並在其餘行中分配循環。 –

+0

我不知道這是怎麼做的 – Damian