静态错误及main方法问题:为何运行Guest而非含main的Hotel
Hey there! Let's work through your Java hotel program issues step by step:
1. Fixing the "No static void main method" error & why Guest is being run
That error pops up because your IDE/compiler is trying to run the Guest class, which doesn't have a main method. Here's why that's happening and how to fix it:
- Most IDEs (like Eclipse, IntelliJ) default to running the class you last edited, or the one you have selected in the project explorer. If you accidentally ran
Guestinstead ofHotel, it'll throw this error. - How to correct this:
- In IntelliJ: Right-click the
Hotelclass file → Select "Run 'Hotel.main()'" - In Eclipse: Right-click
Hotel.java→ "Run As" → "Java Application" - Alternatively, go to your run configurations and set
Hotelas the main class explicitly.
- In IntelliJ: Right-click the
2. Your constructor understanding is correct!
You're right—not all classes need explicit constructors. Java automatically adds a default no-argument constructor to any class that doesn't define its own. For example:
- Your
Roomclass has no explicit constructor, so Java generates a hidden one:Room() {}which lets you createRoomobjects just fine. - You added a custom constructor to
Guest(Guest() { name = "NN"; }), which replaces the default one—this is totally valid if you want to initialize thenamefield by default.
3. A hidden bug to fix (NullPointerException)
Looking at your code, there's one more issue that'll crash your program once you get the main method sorted:
- In the
Hotelconstructor, you create aRoom[]array withrooms = new Room[b];, but this only creates the array itself—each element in the array isnull(no actualRoomobjects exist yet). - When you call
rooms[i].newGuest();in thedemomethod, you'll get aNullPointerExceptionbecause you're trying to call a method on anullobject.
Fix this by initializing each Room in the Hotel constructor:
Hotel(int b){ rooms = new Room[b]; for(int i=0; i<b; i++){ rooms[i] = new Room(); // Create a new Room object for each array slot rooms[i].number = i + 1; // Optional: Set room numbers to 1, 2, 3... instead of 0 } }
With these changes, your program should run correctly: it'll create 4 rooms, let you input guest names for each, and print out each room number with its guest's name.
内容的提问来源于stack exchange,提问作者T.v.L.

