无需注释package语句,如何在Bash中运行带包的Java程序?
问题:带包声明的Java程序在命令行运行失败,如何同时兼容IDE和终端?
我在NetBeans IDE中创建了一个带包声明的Java程序,IDE内运行正常,但在Fedora的Bash命令行用javac编译后,执行java EjerciciosClase时出现以下错误:
Error: Could not find or load main class EjerciciosClase Caused by: java.lang.NoClassDefFoundError: com/estudio/ejerciciosclase/EjerciciosClase (wrong name: EjerciciosClase)
注释掉package com.estudio.ejerciciosclase;语句后程序可正常运行。我希望无需修改代码(保留package语句),同时在NetBeans IDE和Bash终端中都能运行该程序,请问是否有可行方案?
相关代码:
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template */ package com.estudio.ejerciciosclase; import java.util.Scanner; // import the scanner class /** * * @author jfac * */ public class sumScanner { public static void main(String[] args) { int numA, numB, theSum; System.out.println("Program that reads y sums two numbers"); Scanner newObj = new Scanner(System.in); System.out.println("Enter the first number: "); numA = newObj.nextInt(); //String numAString = Integer.toString(numA); System.out.println("Enter the second number: "); numB = newObj.nextInt(); //String numBString = Integer.toString(numB); theSum = numA + numB; // String theSumString = Integer.toString(theSum); System.out.println("The sum of " + numA + " + " + numB + " is equal to " + theSum); } }
解决方案
核心原因是Java要求带包的类必须放在与包名层级一致的目录中,且运行时需从根目录使用全限定类名执行,以下是具体步骤:
1. 匹配包名创建目录结构
包名是com.estudio.ejerciciosclase,需创建对应层级的目录:
你的工作根目录/ └── com/ └── estudio/ └── ejerciciosclase/ └── sumScanner.java
将sumScanner.java文件放入最内层的ejerciciosclase目录中。
2. 从根目录编译代码
回到包含com目录的工作根目录,执行编译命令:
javac com/estudio/ejerciciosclase/sumScanner.java
编译完成后,sumScanner.class文件会自动生成在同一个目录下。
3. 从根目录运行程序
同样在工作根目录下,使用包名+类名的全限定名称执行程序:
java com.estudio.ejerciciosclase.sumScanner
这样操作后,既不需要修改代码(保留包声明),NetBeans IDE因为本身遵循了包目录结构可以正常运行,终端也能成功执行程序。
注意:你错误信息中提到的
EjerciciosClase是笔误,实际主类名是sumScanner,运行时必须使用正确的类名。
内容的提问来源于stack exchange,提问作者Juan
相关产品推荐
相关产品推荐

