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

Java主方法相关运行时错误求助:继承代码调试问题

Java主方法相关运行时错误求助:继承代码调试问题

嘿,我帮你排查了这段代码,发现了几个会导致报错(包括主方法相关问题)的点,咱们一个个说清楚:

一、导致主方法报错的核心原因

你这段代码里包含main方法的Shapes类没有加public修饰符。很多在线Java编辑器对主类的访问权限有严格要求——必须把包含main方法的类声明为public,不然JVM找不到程序的入口点,就会抛出“找不到主方法”或者“无法加载主类”的错误。

二、代码里的逻辑错误(非报错但影响功能)

除了主方法的问题,你的Triangle类里area()方法的实现完全写错了:

double area() {
    return width = height / 2; // 这是赋值语句,不是面积计算!
}

这里你用了赋值运算符=,会把height/2的结果赋值给width,然后返回这个错误的值。三角形面积的正确计算应该是(底×高)/2,所以要改成:

double area() {
    return (width * height) / 2;
}

三、修正后的完整代码

把上面两处改完之后,完整代码应该是这样的:

// A simple class hierachy.
// A class for two-dimentional objects.
class TwoDShape {
    double width;
    double height;

    void showDim() {
        System.out.println("Width and height are " + width + " and " + height);
    }
}

// A subclass of TwoDShape for triangles.
class Triangle extends TwoDShape {
    String style;

    double area() {
        return (width * height) / 2; // 修正面积计算逻辑
    }

    void showStyle() {
        System.out.println("Triangle is " + style);
    }
}

public class Shapes { // 这里添加public修饰符
    public static void main (String args[]) {
        Triangle t1 = new Triangle () ;
        Triangle t2 = new Triangle () ;

        t1.width = 4.0;
        t1.height = 4.0;
        t1.style = "filled";

        t2.width = 8.0;
        t2.height = 12.0;
        t2.style = "outlined";

        System.out.println("info for t1: ");
        t1.showStyle();
        t1.showDim();
        System.out.println("Area is " + t1.area());
        System.out.println();

        System.out.println("info for t2: ");
        t2.showStyle();
        t2.showDim();
        System.out.println("Area is " + t2.area());
    }
}

你把代码换成上面的版本,在在线编辑器里应该就能正常运行了,要是还有其他问题随时问我哈~

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.08 09:04:34