注册 登录
编程论坛 JAVA论坛

求大神帮忙指出一下哪里错了!!!

小白瘤 发布于 2018-10-20 09:47, 2199 次点击
我是初学者,正在学java,但是我按着书上的代码敲,结果它还是会报错,什么缺少;什么需要标识符的。我找了好久还是没找到,已经不知道是什么原因了。
这是程序代码
程序代码:
class Box{
    double width;
    double height;
    double depth;
   
    double volume(){
        return width*height*depth;
    }
   
    void setDim(double w, double h, double d){
        width=w;
        height=h;
        depht=d;
    }
}

class BoxTest{
    public static void main(String[] s)
    Box myBox=new Box();
    Box hisBox=new Box();
    double myVol,hisVol;
    myBox.setDim(10, 20, 15);
    hisBox.setDim(3, 6, 9);
    myVol=myBox.volume();
    hisVol=hisBox.volume();
    System.out.println("myBox is"+myBox);
    System.out.println("hisBox is"+hisBox);
}

只有本站会员才能查看附件,请 登录
4 回复
#2
红柚2018-10-20 12:57
程序代码:

class Box{
    double width;
    double height;
    double depth;
   
    double volume(){
        return width * height * depth;
    }
   
    void setDim(double w, double h, double d){
        width = w;
        height = h;
        depth = d;    //这里你打成depht了
    }
}

public class BoxTest{
    public static void main(String []args){
        Box myBox = new Box();
        Box hisBox = new Box();
        double myVol, hisVol;
        myBox.setDim(10, 20, 15);
        hisBox.setDim(3, 6, 9);
        myVol = myBox.volume();
        hisVol = hisBox.volume();
        System.out.println("myBox is " + myVol);
        System.out.println("hisBox is " + hisVol); //看起来你想要的应该是输出hisVol,但是你的是hisBox,上一行也是这样
    }
}


程序代码:

public class BoxTest {
    public static void main(String[] args) { ... }



现在先记得这个开头吧,main在的类要加public的,后面别忘了要用花括号括起来

[此贴子已经被作者于2018-10-20 13:09编辑过]

#3
wlrjgzs2018-10-20 16:14
2楼正解。不过根据面向对象的封装原则,你那个Box应该修改一下,以符合面向对象的封装原则,代码如下:
程序代码:

class Box{
    private double width;     //这3个成员的访问权限设置为private,不能在类外直接访问,只能通过下面方法进行访问。确保这3个私有成员不被意外赋值。
    private double height;
    private double depth;
   
    double volume(){
        return this.width * this.height * this.depth;
    }
   
    void setDim(double w, double h, double d){
        this.width = w;
        this.height = h;
        this.depth = d;
    }
}
#4
新人学习2018-10-25 17:03
在包含main() 方法 的类前面要加上public 关键字
main() 方法没有用花括号.
#5
陈无2018-10-25 23:06
   加一个public试试,
1