1

用户在命令行和我的 prog 中输入一个文本文件。将获取文本,使用显示的第一个数字的行数(顶点)创建一个数组,然后用剩余的数字填充二维数组。最后它会显示如果#连接到# display T,否则显示F。我还没有完成它,只是填充数组并显示数组中的数字。

import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;


class AdjMatrix {

public static void main(String[] args) {

    //ArrayList<Integer> list = new ArrayList<Integer>(); //Arraylist to store all integers in the array
    //int n = 0; //Vertices
    final int COLS = 2; //Number of columns
    int[][] array = null;
    int lineNumber = 0;
    String line = "";
    if(args.length > 0)
    {
        try
        {
            java.io.File file = new java.io.File(args[0]);
            Scanner in = new Scanner(file);

            //Reading the file
            while(in.hasNext())
                {
                line = in.next();
                lineNumber++;
                if(lineNumber == 1)
                {
                    //n = Integer.parseInt(line);
                    array = new int[Integer.parseInt(line)][COLS];
                    System.out.println(Integer.parseInt(line));
                }
                else
                {
                    String[] tokens = line.split(",");
                    for(int x = 0; x < tokens.length; ++x)
                        for(int j = 0; j < tokens.length; ++j)
                        {
                            array[x][j] = Integer.parseInt(tokens[x]);
                        }
                }

            }
            in.close();
        }//End try 
        catch(FileNotFoundException e)
        {
            System.err.println("File was either not found or it does not exist.");
            System.out.printf("\n");

        }//End catch
    }//End Commandline param entry


    for(int i = 0; i < array.length; i++)
        for(int j = 0; j < array.length; j++)
            System.out.println(" " + array[i][j]);


}
}

我输入System.out.println(Integer.parseInt(line));看看它是否抓取了数字并将其放入数组的行#中,这是成功的。任何帮助表示赞赏。已经有一段时间了,感谢您提供任何帮助。

编辑 对不起,忘记添加输入文件。

整数.txt

9
1,2
2,6
6,2
5,1
6,5
3,2
6,3
3,7
8,7
9,9

9 是确定行数的数字。然后程序抓取 9 之后的所有数字

4

1 回答 1

1

看起来您正在初始化一个firstLine2维数组,

array = new int[Integer.parseInt(line)][COLS];

但你试图用line.length元素line.length填充它。

for(int x = 0; x < tokens.length; ++x)
    for(int j = 0; j < tokens.length; ++j)
    {
        array[x][j] = Integer.parseInt(tokens[x]);
    }

这似乎是一个错误,但没有看到示例文件,我不能肯定地说。

于 2013-10-17T17:09:23.343 回答