簡體   English   中英

鄰接矩陣Java

[英]Adjacency Matrix 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之后的所有數字

似乎您正在初始化firstLine by 2維數組,

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

但是您正在嘗試使用line.lengthline.length元素填充它。

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

這似乎是一個錯誤,但沒有看到示例文件,我不能肯定地說。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM