Java类文件在IntelliJ项目内可运行,移出项目则无法运行
Hey there, let's break down why your code runs perfectly in your IntelliJ "Quiz 1" project but gives no output when you move HospitalTester.java alone, plus how to fix it:
1. You're Missing the Compiled Hospital Class File
Your code packs two top-level classes (HospitalTester and Hospital) into a single .java file. When IntelliJ compiles your code, it automatically generates two separate .class files: HospitalTester.class and Hospital.class.
If you only move the .java file and compile it manually (or forget to include the Hospital.class file when running), the JVM can't find the Hospital class it needs to instantiate. While this should throw a NoClassDefFoundError, sometimes terminal output can get buried or you might miss the error message, making it look like there's no output at all.
Fix: When you compile HospitalTester.java via the command line with javac HospitalTester.java, make sure both generated .class files stay in the same directory. Run java HospitalTester only from that directory.
2. The Program Is Waiting for Your Input (Most Likely Culprit)
Look at your setName(), setNumberOfDoctors(), etc., methods—each one prompts you for input and waits for you to type something:
public void setName() { System.out.print("Enter a new name for the hospital: \n"); this.name = new Scanner(System.in).nextLine(); }
When you run the program in a terminal, it prints the first prompt and pauses, waiting for you to enter the hospital name. If you don't notice the prompt (or your terminal isn't displaying it correctly), it looks like the program is doing nothing.
Quick Test: Run the program again, type any hospital name, hit enter, and you'll see the next prompt pop up, followed by all your expected output once you finish entering all values.
Pro Tip: Your current code creates a new Scanner instance every time you call a set method, which can cause weird input bugs (like leftover newline characters messing up subsequent inputs). Instead, create one Scanner in your main method and pass it to each set method:
// In HospitalTester's main: Scanner inputScanner = new Scanner(System.in); hospital.setName(inputScanner); hospital.setNumberOfDoctors(inputScanner); // ... repeat for other set methods // Update Hospital's set methods to accept the Scanner: public void setName(Scanner scanner) { System.out.print("Enter a new name for the hospital: \n"); this.name = scanner.nextLine(); }
This makes your input logic more reliable and avoids unexpected issues.
3. Wrong Working Directory When Running
If you run java HospitalTester from a directory that doesn't contain the compiled .class files, the JVM can't find your classes. Again, this might show an error or appear as no output depending on your setup.
Fix: Navigate to the directory where your .class files live using cd in the terminal before running the java command.
内容的提问来源于stack exchange,提问作者Evan Kim

