我对Scala真的很陌生,所以对大多数人来说这似乎是显而易见的,但这是我的问题。我创建了一个简单的类来为汉堡卡车创建门票:
class Tickets() {
var burgerPrice = 2.00
var frenchFriesPrice = 1.00
var milkshakePrice = 3.00
var taxes = 0.08
def calculatePrices(burgersNum: Int, frenchFriesNum: Int, milkshakesNum: Int) = {
val price = (burgersNum*burgerPrice + frenchFriesNum*frenchFriesPrice + milkshakesNum*milkshakePrice) * (1+taxes)
price
}
}
我在这里要完成的是现在在对象内创建一个函数来打印小计和每张收据的总价。为了做到这一点,我试过了:
object receipt{
def main(args: Array[String]) {
val importe = new Tickets()
val burgersNum = readLine("Welcome to my shop. How many burgers do you want? ").toInt
val frenchFriesNum = readLine("How many French fries? ").toInt
val milkshakesNum = readLine("Any milkshakes? ").toInt
println("Burgers: " + burgersNum + "Price: " + Tickets.burgerPrice)
}
}
但是试图访问Tickets中的变量以获得价格似乎不起作用。我有一个简单的方法吗?
答案 0 :(得分:0)
您只需调用对象的方法来获取结果,这就是您缺少的内容,请参阅以下示例中的importe.calculatePrices(3, 4, 5)
object receipt {
def main(args: Array[String]) {
val importe = new Tickets()
val burgersNum = readLine("Welcome to my shop. How many burgers do you want? ").toInt
val frenchFriesNum = readLine("How many French fries? ").toInt
val milkshakesNum = readLine("Any milkshakes? ").toInt
println("Burgers: " + burgersNum + "Price: " + importe.calculatePrices(burgersNum, frenchFriesNum, milkshakesNum))
}
}
阅读java或scala中的OOP。
https://www.scala-exercises.org/scala_tutorial/object_oriented_programming