2014-02-24 78 views
1

我需要幫助完成作業。請注意,我已經完成了自己的代碼,但不知道我是否正確地做了,尤其是我家庭作業的最後一句話。對象和屬性值

我的家庭作業:

定義一個叫建立具有以下屬性類。每座建築都有一個平方英尺(面積)和故事。構造函數使用這兩個屬性創建一個Building。方法get_squarefootage(),get_stories(),set_square_footage()和set_stories()將用於獲取和設置各自的屬性值。方法get_info()將返回建築物的所有當前屬性值。 編寫一個程序,讓用戶創建Building對象並更改其屬性值。

package building_hw2; 

import java.util.Scanner; 

public class Building { 

    int area; 
    int stories; 

    int get_squarefootage() { //get values of the area 
     return area; 
    } 

    int get_stories() { //get values of the stories 
     return stories; 
    } 

    void set_square_footage(int area) { //set values of the area 
     this.area = area; 
    } 

    void set_stories(int stories) { //set values of the stories 
     this.stories = stories; 
    } 

    void get_info() { //return all the current attribute balues of the building 
     System.out.println("The square footage of the building is " + area); 
     System.out.println("The building has " + stories + " stories"); 
    } 

    //main method 
public static void main(String[] args) { 

    Building Bldg = new Building(); //create a building object 

    Bldg.area = 40000; 
    Bldg.stories = 5; 

    Bldg.get_info(); //display the current values of the building 

    //get user input to create building object 
    Scanner keybd = new Scanner(System.in); 
    System.out.println("Please enter the square footage(area) of the building : "); 
    int bldgArea = keybd.nextInt(); 

    System.out.println("Please enter the stories : "); 
    int bldgStories = keybd.nextInt(); 

    Bldg.set_square_footage(bldgArea); 
    Bldg.set_stories(bldgStories); 

    Bldg.get_squarefootage(); 
    Bldg.get_stories(); 

    Bldg.get_info(); 
} 

} 
+1

而你的問題是... –

+0

我是否根據需求編寫代碼?對不起,我知道這聽起來很愚蠢,但它是什麼:) – Insane

+0

我不理解他說「讓用戶創建建築物」的部分 – Insane

回答

1

get_info要麼返回一個String或重命名爲printBuildingAttributes

您有Bldg.area,但爲什麼沒有該字段的setter方法?這將與你的getter/setter範例一起工作。它看起來像你已經擁有它,所以使用它。使領域本身是私人的,只能通過你的getter/setter方法訪問。

如果您要檢索建築物的層數或面積,您需要將其存儲在一個變量中。現在,您正在檢索它並將其扔掉。

此外,get_infoget_area不是方法命名的正確Java慣例。

2

你很困惑「返回」和「打印到控制檯」。 get_info()方法應該返回一些東西。它不應該打印任何東西。

字段應該是私人的。在這種情況下,方法應該是公開的,因爲您希望任何其他類能夠調用它們。你忘了提供一個構造函數,雖然你的老師要求你提供一個構造函數。

請通知您的老師Java中存在命名約定,而教授其他約定根本不是一個好主意。許多框架和API假定遵守標準約定。 get_squarefootage()應該被命名爲getSquareFootage()。二傳手相同。使用真實的單詞,以小寫字母開頭,代表變量:building,而不是Bldg

+0

當然[這裏是來自Sun/Oracle的官方代碼約定](http://www.oracle.com/technetwork/java/codeconv-138413.html)。 – Radiodef

3

你似乎正在做的正確。不過,我想指出一些事情。首先,你應該聲明成員變量爲私有的,以便更好地封裝你的類。您已經有更改屬性值的setter方法。

int area; 
int stories; 

在你的主,你可以如下設置建築物值:

Bldg.set_square_footage_area(40000); 
Bldg.set_stories(5); 

爲的get_info要求也不是很清楚,你應該問,究竟應該返回(屬性或只是一些字符串表示打印所有屬性的當前值)

+0

我沒有問他以下幾點:嗨教授, 我要澄清: 「的方法的get_info()將返回大樓的所有當前屬性值」 - 當程序運行時,它應該顯示目前的squarefootage和建築物給使用者的故事(例如,目前,這座建築是40000平方英尺,有8層樓) - 這是你要求我們做的嗎?此外,你是否還要求我們計算建築物中每個故事的總平方? – Insane

+0

如果一棟建築物有8層樓,總平方面積爲40000,那麼程序是否應該顯示每層樓的面積是5000平方英尺?他的迴應是:顯示總平方英尺。這就對了。 – Insane

+0

在這種情況下,你正在做什麼需要在get_info – Kakarot