类 和对象的基础知识:Java

Basics of classes and objects: Java

我收到的问题:

定义具有以下规格的 class 酒店:

私人成员:

Roomno            
Name
Charges_day     
No_of_days     

Public 成员:

Getit()      -to enter the data members
Showit()  to show the data member
Compute()   -To calculate and return the total charges as charges_day * No_of_days

和一个初始化数据成员的构造函数。


我写的代码:

public class hotel{
    private int Roomno;
    private String Name; 
    private int Charges_day; 
    private int No_of_days;

    public hotel(){
        Roomno = 0; 
        Name = "";
        Charges_day = 0;
        No_of_days = 0; 
    }

    public void Getit(int r, String n, int c, int no){
        Roomno = r; 
        Name = n;
        Charges_day = c;
        No_of_days = no;
    }

    public String Showname(){
        return Name;
    }
    public int  Showit(){
        return Roomno;
        return Charges_day;
        return No_of_days;
    }

    public int Compute(){
        return (Charges_day*No_of_days); 
    }

}

我知道在一个方法函数中不能有超过 1 个 returns,但我找不到解决这个问题的方法。

关于要求,我建议您只打印值

public void Showit(){
    System.out.println(Name+" "+Roomno+" "+Charges_day+" "+No_of_days);
}

如果您需要一个 return 对象的 String 表示的方法,请覆盖 toString()

public String toString(){
    return Name + " " + Roomno + " " + Charges_day + " " + No_of_days;
}

另外 Java 命名约定是

  • 方法和属性的 lowerCamelCase