【发布时间】:2022-01-08 23:44:34
【问题描述】:
我想知道为什么我的代码在https://www.onlinegdb.com/online_java_compiler 上完美运行,但在 Visual Studio Code 上似乎有一个错误:
线程“main”中的异常 java.lang.NoSuchMethodError: 'int GenericTree.height()' 在 SimpleTree02.main(SimpleTree02.java:7)
我不明白为什么网站上没有错误,尽管我已经检查并仔细检查过,似乎没有错误。我从 youtube 视频中复制了代码,所以它应该 100% 工作,尽管这仍然有这个错误。我希望有人能帮助我,我真的快疯了。提前致谢!
代码如下:
import java.util.*;
// Height of a Generic Trees
public class Main {
public static void main(String[] args) {
GenericTree tree = new GenericTree();
// tree.display();
int h = tree.height();
System.out.println(h);
}
}
class GenericTree {
class Node {
int data;
ArrayList <Node> children;
Node(int data) {
this.data = data;
children = new ArrayList <> ();
}
}
private Node root;
GenericTree() {
Scanner s = new Scanner(System.in);
this.root = ConstructorGT(s, null, 0);
}
private Node ConstructorGT(Scanner s, Node parent, int i) {
if(parent == null) {
System.out.println("Enter the data for the root node...");
} else {
System.out.println("Enter the data for the "+ i +"th child of the "+parent.data);
}
int data = s.nextInt();
Node node = new Node(data);
System.out.println("Enter the number of children of "+node.data);
int n = s.nextInt();
for(int j = 0; j < n; j++) {
Node child = ConstructorGT(s, node, j);
node.children.add(child);
}
return node;
}
public void display() {
display(this.root);
}
private void display(Node node) {
String str = node.data + " => ";
for(Node child: node.children) {
str += child.data + ", ";
}
System.out.println(str);
for(Node child: node.children) {
display(child);
}
}
public int height() {
return this.height(root);
}
private int height(Node node) {
int th = 0;
for(Node child: node.children) {
int ch = height(child);
if(ch > th)
th = ch;
}
return th+1;
}
}
【问题讨论】:
-
您确定它确实重新编译了您的代码吗?也许删除 out 文件夹。或者更好的是,使用真正的 IDE。
-
“我从 youtube 视频中复制了代码,因此它应该 100% 正常工作......” - 该逻辑至少存在三个缺陷。 :-)
-
代码可以在我的VS Code中成功运行。从以下几个方面检查: 1. java 文件应该是
Main.java。 2Java: Clean Java Language Server Workspace来自 VS Code 中的命令面板。看看有没有帮助。