用户在命令行和我的编上输入文本文件。将获取文本,使用显示的第一个数字的行数(顶点)创建一个数组,然后用剩余的数字填充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
维数组初始化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]);
}
这似乎是一个错误,但是没有看到示例文件,我不能肯定地说。
关于java - 邻接矩阵Java,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19432904/