邻接矩阵java

时间:2013-10-17 17:01:09

标签: java

用户在命令行和我的编程中输入文本文件。将获取文本,创建一个显示第一个数字的行数(顶点)的数组,然后用剩余的数字填充2d数组。最后,如果连接到显示 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));以查看它是否抓取数字并将其放入数组的行#,这是成功的。任何帮助表示赞赏。对它感兴趣并且感谢任何帮助。

修改 对不起,忘了添加输入文件。

integer.txt

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

9是建立行数的数字。然后该程序在9

之后抓取所有数字

1 个答案:

答案 0 :(得分:1)

您似乎正在初始化firstLine 2尺寸数组,

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

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