2015-12-01 33 views
0

如何創建一個庫存類,該庫有兩個方法(加減法),它將一個金額加上或減去一個Item類,並返回一個新的Item,其計數調整正確?如何用包含2個方法的類修改現有的類?

語言:斯卡拉

什麼代碼應該做的:

val Shirts = Item("Hanes", 12) 

val Inv = new Inventory 

scala> Inv.subtract(5, Shirts) 

output: Item(Hanes,7) 

scala> Inv.add(5, Shirts) 

output: Item(Hanes,17) 

的代碼,我有:

case class Item(val brand: String, val count: Int) 

class Inventory { 
    def add(amount:Int):Int={ 
    count+=amount 
    } 

    def subtract(amount:Int):Int={ 
    count-= amount 
    } 
} 

注:我無法弄清楚如何修改項目類庫存類包含2個方法。任何幫助表示讚賞。

+0

Scott,您必須將所有代碼放在代碼語法高亮顯示中。請修復。 –

+0

Ashwin,原諒我,我還在學習。它看起來像有人修復它,我會在下一次這樣做。 –

+0

不,這都是好人!只是讓你知道,所以回答你的問題更容易。 –

回答

2

這應該做的工作:

class Inventory { 
    def add(amount:Int, item: Item): Item = { 
    item.copy(count = item.count+amount)  
    } 

    def subtract(amount:Int, item: Item): Item = { 
    item.copy(count = item.count-amount) 
    } 
} 

編輯:按你的意見,增加一個檢查量> 0(如果金額< = 0,我只需將項目不變) :

class Inventory { 
    def add(amount:Int, item: Item): Item = { 
    if (amount > 0) item.copy(count = item.count+amount) else item 
    } 

    def subtract(amount:Int, item: Item): Item = { 
    if (amount > 0) item.copy(count = item.count-amount) else item 
    } 
} 
+0

如何在代碼中添加if語句?例如,當金額必須大於0.當我添加if else語句時,會出現類型不匹配錯誤。 –

+0

@ScottWright我編輯了我的答案,以顯示一個直接的方式,如果其他可以納入。 – Shadowlands

+0

太棒了,謝謝。 –

相關問題