我尝试在cmd中执行Java程序,但使用“java”运行程序时出现错误

问题描述 投票:0回答:1

我可以在 VS code 中成功运行该程序: run in vs code

命令:

/usr/bin/env /usr/lib/jvm/java-17-openjdk-amd64/bin/java -XX:+ShowCodeDetailsInExceptionMessages -cp /home/bignosecss/.vscode-server/data/User/workspaceStorage/766f1605a62c4e70ce2260ed71260df5/redhat.java/jdt_ws/JavaFundamentals_e17aac68/bin IntList.IntList  5 10 15

输出及异常信息:

The 0th number of int list is: 5 The 1th number of int list is: 10 The 2th number of int list is: 15 Exception in thread "main" java.lang.NullPointerException: Cannot read field "first" because "copyIntList" is null at IntList.IntList.get(IntList.java:39) at IntList.IntList.main(IntList.java:49)

但是在cmd(WSL2-Ubuntu)中出现错误: run in cmd

命令:

java IntList 5 10 15

错误信息:

Error: Could not find or load main class IntList Caused by: java.lang.NoClassDefFoundError: IntList/IntList (wrong name: IntList)

代码:

package IntList;

public class IntList {

    public int first;
    public IntList rest;

    public IntList(int f, IntList r) {
        this.first = f;
        this.rest = r;
    }

    public int size() {
        if (this.rest == null) {
            return 1;
        } else {
            return 1 + this.rest.size();
        }
    }

    public int iterativeSize() {
        IntList copyListP = this;
        int size = 1;
        while (copyListP != null) {
            size = size + 1;
            copyListP = copyListP.rest;
        }
        return size;
    }

    public int get(int i) {
        IntList copyIntList = this;
        if (i == 0) {
            return copyIntList.first;
        } else {
            for (int j = 1; j <= i; j++) {
                copyIntList = copyIntList.rest;
            }
            return copyIntList.first;
        }
    }

    public static void main(String[] args) {
        IntList L = new IntList(Integer.parseInt(args[0]), null);
        L.rest = new IntList(Integer.parseInt(args[1]), null);
        L.rest.rest = new IntList(Integer.parseInt(args[2]), null);

        for (int x = 0; x <= L.size(); x++) {
            System.out.println("The " + x + "th number of int list is: " + L.get(x));
        }

    }

}

起初,我认为重要的是包名称,然后我将包名称更改为与

IntList.java
相同。这也不是问题。 我尝试将main方法写到同一个包下的另一个文件中,编译不通过。

java jvm windows-subsystem-for-linux wsl-2
1个回答
0
投票

从包结构的根设置类的完整路径,例如:

java -cp /path/to/root/of/package/structure IntList.IntList 5 10 15
还要检查您是否有包含 IntList.class 文件的 IntList 文件夹

© www.soinside.com 2019 - 2024. All rights reserved.