我在file.how中有一个图形的邻接矩阵,用于将这个邻接矩阵存储在二维矩阵中 我的输入文件看起来像
e 1 36
e 2 45
e 3 74
e 4 18
e 5 36
e 6 74
e 6 45
e 6 136
e 6 36
e 6 21
e 6 18
e 7 18
e 7 116
e 7 74
e 7 99
e 7 81
e 7 135
我需要一个输出作为邻接列表:
1-->36
2-->45
3-->74
4-->18
5-->36
6-->74-->45-->136-->36-->21-->18
7-->18-->116--->74-->99-->81-->135
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.StringTokenizer;
public class Graph1 {
public static void main(String[] args) throws FileNotFoundException {
int linecount = 0, ec = 0;
String nbin = null, cbin = null;
int[][] data = null;
String e = "e";
System.out.println("Graph Coloring Algorithm Test\n");
Scanner sc = new Scanner(System.in);
System.out.print("Enter graph input file name: ");
String newfile = sc.nextLine() + ".txt";
File file = new File(newfile);
Scanner scan = new Scanner(file);
while ((scan.hasNext())) {
StringTokenizer t = new StringTokenizer(scan.nextLine());
if (t.nextToken().equals(e)) {
ec++;
nbin = scan.nextInt();
cbin = scan.nextInt();
}
linecount++;
for (int i = 0; i < 5; ++i)
for (int j = 0; j < 5; ++j) {
{
data[nbin][cbin] = 1;
}
}
}
for (int i = 0; i < 5; ++i)
for (int j = 0; j < 5; ++j) {
{
System.out.print(data[i][j]);
}
}
}
}
此代码有错误.how将字符串标记转换为整数 我如何接受以 e 开头的文件行并将其添加到邻接列表中。
答案 0 :(得分:0)
在代码的第19行,您不应该使用scan.nextLine()
而应使用scan.next()
,因为它是您正在使用的迭代器。
并且在第22,23行,您使用scan.nextInt()
并尝试将其吸引到字符串。除非你想让用户输入一个Integer,你应该使用你在第19行指定的相同String。我假设你的意思是'e'之后的整数,所以你需要这样做:
StringTokenizer t = new StringTokenizer(scan.next());
if (t.nextToken().equals(e)) {
ec++;
nbin = Integer.valueOf(t.nextToken());
cbin = Integer.valueOf(t.nextToken());
}
你需要改变nbin&amp; cbin到整数,以便它工作。并且您的二维数组始终为null。您需要添加int[][] data = new int[Your First Size][Your Second Size];
计算邻接列表的逻辑不起作用,因为根据你的“矩阵输入文件”,整数大于0-5。相反,我建议您使用Maps.
好的,这会让你更接近你的目标,但你需要自己做,以便了解和学习一些东西,所以我会留下你的。
另请参阅: Java Docummentations