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

Java公共类声明错误:类与文件名不匹配问题求助

搞定 "class is public, should be declared in a file named..." 错误+代码优化指南

一、先解决核心的编译错误

你碰到的这个错误是Java的死规矩:public类的名字必须和文件名完全一模一样,连大小写都不能错。虽然你说已经存成PastPresentFuture.java了,但还是得排查这几个容易踩的坑:

  • 检查文件名大小写:如果用的是Linux或者Mac系统,文件名是区分大小写的,比如不小心写成pastpresentfuture.java或者PastPresentfuture.java都会触发错误,一定要确保每个单词的首字母都大写,和类名完全匹配。
  • 别被隐藏后缀坑了:有些编辑器会偷偷给文件加额外后缀,比如PastPresentFuture.java.txt,这时候系统认的是.txt结尾的文件,自然会报错。去文件管理器里开一下“显示文件扩展名”,确认文件名没错。
  • 再核对代码里的类声明:确保public class PastPresentFuture这一行没拼写错,类名和文件名必须丝毫不差。

二、顺便把代码功能给修对

除了编译问题,我看你代码里还有几个小问题,导致它没法正确判断日期是过去、现在还是未来:

  1. 输入提示完全不对:你现在写的System.out.print("May");,用户看到一脸懵,根本不知道要输入啥,得改成明确的提示,比如“Enter month: ”。
  2. 输出逻辑跑偏了:现在的代码只是把数字加起来输出,完全没实现“判断日期是过去/现在/未来”的需求,得把逻辑改对。

下面是修复好的完整代码,直接用就行:

//Name
//Date
//Chapter and problem #
//Application prompts user to enter month, day, year
import java.util.*;
import java.time.LocalDate;

public class PastPresentFuture {
    public static void main (String[] args) {
        LocalDate today = LocalDate.now(); 
        int mo, da, yr;
        int todayMo = today.getMonthValue();
        int todayDa = today.getDayOfMonth();
        int todayYr = today.getYear();
        
        Scanner input = new Scanner(System.in);
        
        // 清晰的输入提示,用户一看就懂
        System.out.print("Enter month: ");
        mo = input.nextInt();
        System.out.print("Enter day: ");
        da = input.nextInt();
        System.out.print("Enter year: ");
        yr = input.nextInt();
        
        // 一步步判断日期是过去、现在还是未来
        if (yr < todayYr) {
            System.out.println("The date is in the past.");
        } else if (yr > todayYr) {
            System.out.println("The date is in the future.");
        } else {
            // 年份相同,就比月份
            if (mo < todayMo) {
                System.out.println("The date is in the past.");
            } else if (mo > todayMo) {
                System.out.println("The date is in the future.");
            } else {
                // 月份也相同,就比日期
                if (da < todayDa) {
                    System.out.println("The date is in the past.");
                } else if (da > todayDa) {
                    System.out.println("The date is in the future.");
                } else {
                    System.out.println("The date is today!");
                }
            }
        }
        input.close(); // 用完Scanner记得关掉,养成好习惯
    }
}

三、最后说下编译运行的正确步骤

  1. 确保文件老老实实保存成PastPresentFuture.java(大小写一个都不能错)。
  2. 打开命令行,进到这个文件所在的文件夹,先编译:
    javac PastPresentFuture.java
    
  3. 编译成功后,运行程序:
    java PastPresentFuture
    
    然后跟着提示输入月份、日期、年份,就能得到正确的判断结果啦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:41:12