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

如何解决Java '.class' expected错误及编译失败问题

Fixing Your Two-Number Sum Java Compilation Error

Hey there! Let's sort out that compilation error you're hitting with your sum program. The root of the issue is in your main method—let's break down what's wrong and how to fix it easily.

What's Causing the Error?

  • main method can't return a value: The main method is defined as void, which means it shouldn't return anything at all. Your line return int ad(); is totally invalid here—return doesn't belong here, and the syntax for calling your method is wrong too.
  • Incorrect method call: Your ad method is an instance method (not static), so you need to create an object of the Sum class first to call it. You also have to pass two integer arguments to it, since that's how you defined the method.
  • Unused instance variables: The a, b, and add variables you declared at the top of the class aren't being used for anything—your ad method uses its own parameters, so those class-level variables are just cluttering up the code.

Corrected Code

Here's the fixed version with explanations of the changes:

public class Sum { 
    // Removed unused instance variables to clean up the code
    public int addNumbers(int a, int b){ // Renamed to a more readable name (optional but recommended)
        int sum = a + b; // No need for (int) cast—parameters are already ints!
        return sum;
    } 
    public static void main(String[] args) { 
        // 1. Create an instance of the Sum class
        Sum sumCalculator = new Sum();
        // 2. Call the add method with actual numbers (e.g., 4 and 6)
        int result = sumCalculator.addNumbers(4, 6);
        // 3. Print the result so you can see the output
        System.out.println("Total sum: " + result);
    } 
}

Key Fixes Explained

  1. Removed redundant variables: Got rid of the unused class-level a, b, and add since they weren't contributing anything.
  2. Cleaned up the method: Renamed ad to addNumbers for clarity (feel free to change it back if you prefer, but descriptive names make code easier to maintain). Also removed the unnecessary (int) cast—since a and b are already int values, their sum is automatically an int.
  3. Fixed the main method:
    • Created an instance of Sum (sumCalculator) because we need an object to call the non-static addNumbers method.
    • Properly called the method with two integer arguments and stored the result in result.
    • Added a System.out.println statement to display the sum—this way you can actually see the program's output when it runs.
    • Removed the invalid return line entirely, since main is a void method.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 00:37:56