我有一个编码图表矩阵的任务,它使数字标记它们并吐出连接。现在有这个非静态/静态的基本问题。即使我认为我理解了类和该类的实例之间的区别,我也不明白这个问题。当我运行它时,首先出现循环问题。不会暂停输入标签。我感谢任何帮助和/或批评。
public class GraphMatrix {
class Matrix {
private int matrix[][];
private int size;
private String labels[];
private void createMatrix() {
Scanner in = new Scanner(System.in);
System.out.println("How many points will be represented in this graph?");
size = in.nextInt();
matrix = new int[size][size];
labels = new String[size];
System.out.println("Please label each point.");
for (int i = 1; i <= size; i++) {
System.out.println("Enter label for point #" + (i));
String key = in.nextLine();
labels[i] = key;
}
System.out.println("Please define edges between points or enter -1 when finished:");
int finish = 1;
while (finish == 1) {
int jkey = 0;
int kkey = 0;
int count = 0;
boolean pass = false;
System.out.println("Point labeled:");
String j = in.nextLine();
while (pass = false) {
if (labels[count].equals(j)) {
jkey = count;
count = 0;
pass = true;
}
}
System.out.println("to point labeled:");
String k = in.nextLine();
while (pass = true) {
if (labels[count].equals(j)) {
kkey = count;
pass = false;
}
}
matrix[jkey][kkey] = 1;
System.out.println("Finished enter -1, to define more connections enter 1");
finish = in.nextInt();
}
}
private void listEdges() {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (matrix[i][j] == 1) {
System.out.println("There is an edge between" + labels[i] + " and" + labels[j]);
}
}
}
}
}
public static void main(String[] args) {
Matrix neo = new Matrix();
neo.createMatrix();
neo.listEdges();
}
}
答案 0 :(得分:2)
您需要在 main 方法中进行如下更改,以消除编译器错误。
这
Matrix neo = new Matrix();
到
GraphMatrix graphMatrix = new GraphMatrix();
Matrix neo = graphMatrix.new Matrix();
注意:要实例化内部类,必须首先实例化外部类。然后,使用以下语法在外部对象中创建内部对象:
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
答案 1 :(得分:0)
我在您的代码中看到了一个重要问题。
此while (pass = false) {
应为while (!pass) {
和while (pass = true) {
应为while (pass) {
另外:为什么要将Matrix类嵌套在GraphMatrix类中?这对我来说没有意义。如果我是你,我不会这样做,除非它明确要求你的任务。