0

我从文件中读取有很大的问题。我在文件中的数据看起来像

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();          
    }

}

4

1 回答 1

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 命名约定。

于 2013-10-22T16:25:46.930 回答