2013-03-28 18 views
0

所以我有这个变量,currentPartNumber,它开始等于0.我想要发生的是在我的函数中,如果变量等于零,它将更改为1,并将文本打印出来。我的第二个功能是一样的 - 如果在我的第一个功能中变量变为1,并且等于1,我希望变量变为2,打印出文本。如何在scala变更中创建变量?

问题是:如何让我的变量随每个函数调用而改变?

var currentPartNumber = 0 

def roomOne():Unit = { 
    if (currentPartNumber < 1) { 
     var currentPartNumber = 1 
     println("You now have parts 1 of 4.") 
    } else { 
     println("This part cannot be collected yet.") 
    { 
    } 


def roomTwo():Unit = { 
    if (currentPartNumber = 1) { 
     var currentPartNumber = 2 
     println("You now have parts 2 of 4.") 
    } else { 
     println("This part cannot be collected yet.") 
    { 
    } 

回答

1

的一类,其中roomOne()roomTwo()可以访问和修改其声明currentPartNumber

class Parts{ 
    var currentPartNumber = 0 

    def roomOne():Unit = { 
    if (currentPartNumber < 1) { 
     currentPartNumber = 1 
     println("You now have parts 1 of 4.") 
    } else { 
     println("This part cannot be collected yet.") 
    } 
    } 

    def roomTwo():Unit = { 
    if (currentPartNumber == 1) { 
     currentPartNumber = 2 
     println("You now have parts 2 of 4.") 
    } else { 
     println("This part cannot be collected yet.") 
    } 
    } 
} 



scala> :load Parts.scala 
Loading Parts.scala... 
defined class Parts 
scala> var parts = new Parts 
parts: Parts = [email protected] 
scala> parts.currentPartNumber 
res0: Int = 0 
scala> parts.roomOne 
You now have parts 1 of 4. 
scala> parts.roomTwo 
You now have parts 2 of 4. 
+0

这有效,但我的情况非常简单,所以其他答案工作得很好。虽然谢谢! – Chris 2013-03-28 04:56:42