首页 > 解决方案 > Basics of classes and objects: Java

问题描述

The question that I received:

Define a class hotel with the following specifications:

Private members:

Roomno            
Name
Charges_day     
No_of_days     

Public members:

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

and a constructor function to initialize the data members.


The code I wrote:

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); 
    }

}

I am aware that I can't have more than 1 returns in one method function, but I'm unable to find a way around this.

标签: javaclassobjectpublic

解决方案


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

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

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

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

Java命名约定也是

  • 方法和属性的 lowerCamelCase

推荐阅读