You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

静态错误及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 Guest instead of Hotel, it'll throw this error.
  • How to correct this:
    • In IntelliJ: Right-click the Hotel class file → Select "Run 'Hotel.main()'"
    • In Eclipse: Right-click Hotel.java → "Run As" → "Java Application"
    • Alternatively, go to your run configurations and set Hotel as the main class explicitly.

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 Room class has no explicit constructor, so Java generates a hidden one: Room() {} which lets you create Room objects 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 the name field 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 Hotel constructor, you create a Room[] array with rooms = new Room[b];, but this only creates the array itself—each element in the array is null (no actual Room objects exist yet).
  • When you call rooms[i].newGuest(); in the demo method, you'll get a NullPointerException because you're trying to call a method on a null object.

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.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:08:56