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

使用OnlineGDB编译Java折扣计算程序时遇Main类编译错误求助

解决OnlineGDB中Java编译错误:Main.java必须包含名为'Main'的public类

错误根源在于你代码中的package java_conditional;声明与OnlineGDB的编译规则冲突:

  • OnlineGDB默认将单个Java文件视为默认包下的类,当你添加包声明后,编译器会期望该文件位于java_conditional目录下,但你未创建对应目录结构,导致编译器无法定位到正确的Main类。

修复方案一(最简单):移除包声明

直接删除代码第一行的package java_conditional;,修改后的代码如下:

import java.util.Scanner; 
public class Main
{
    public static void main (String[]args) { 
            Scanner scan = new Scanner(System.in); 
            System.out.print("Enter Tution fee: "); 
            int tuition = scan.nextInt(); 
             
            System.out.print("  Scholar Type:\n\n1 Scholar1 80%\n2 Scholar2 50%\n3 Scholar1 25%\nEnter Scholar: "); 
            int scholar = scan.nextInt(); 
             
            switch(scholar) {              
                case 1: 
                    int scholar1 = (80*tuition)/100; 
                    System.out.println("Discounted ("+scholar1+") 80% of "+tuition); 
                    System.out.println("the tuition fee you just have to pay is only "+(tuition-scholar1)); 
                    break; 
             
                case 2: 
                    int scholar2 = (50*tuition)/100; 
                    System.out.println("Discounted ("+scholar2+") 50% of "+tuition); 
                    System.out.println("the tuition fee you just have to pay is only "+(tuition-scholar2)); 
                    break; 
                 
                case 3: 
                    int scholar3 = (25*tuition)/100; 
                    System.out.println("Discounted ("+scholar3+") 25% of "+tuition); 
                    System.out.println("the tuition fee you just have to pay is only "+(tuition-scholar3)); 
                    break; 
                 
                default: 
                    System.out.println("Not grantee "); 
            }
    }
}

修复方案二(保留包声明):创建对应目录结构

如果你需要保留包声明,需在OnlineGDB中手动匹配包结构:

  1. 点击左侧文件树的New Folder按钮,创建java_conditional文件夹
  2. 将你的Main.java文件移动到该文件夹内
  3. 重新编译运行即可

内容的提问来源于stack exchange,提问作者user17329175

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 08:06:22