gpt4 book ai didi

java - 邻接矩阵java

转载 作者:太空宇宙 更新时间:2023-11-04 07:20:20 24 4
gpt4 key购买 nike

用户在命令行和我的 prog.txt 中输入一个文本文件。将获取文本,创建一个包含显示的第一个数字的行数(顶点)的数组,然后用剩余的数字填充二维数组。最后显示如果#连接到#则显示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));来查看它是否获取数字并将其放入数组的rows #中,这是成功的。任何帮助表示赞赏。已经使用了一段时间,非常感谢任何帮助。

编辑抱歉,忘记添加输入文件。

整数.txt

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

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

最佳答案

看起来您正在通过 2 维数组初始化 firstLine

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

但您试图用 line.length by 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]);
}

这看起来像是一个错误,但在没有看到示例文件的情况下,我无法确定。

关于java - 邻接矩阵java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19432904/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com