如果在Android Studio中使用时需要成员声明

时间:2019-09-18 13:37:36

标签: android kotlin

我已经开始学习Android。 我在Kotlin中无法使用if,因为我看到了此错误 期待成员声明 你能帮我吗??

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }

    var fixedIncome : Int = 50
    var tips : Int = 20
    var income : Int = fixedIncome + tips

    if(tips == 0){
        Log.d("tag", "You have not recieved any tips today")
    } else {
        Log.d("tag", "You have recieved some tips today")
    }
}

1 个答案:

答案 0 :(得分:1)

你不能写:

if(tips == 0){
    Log.d("tag", "You have not recieved any tips today")
}else{
    Log.d("tag", "You have recieved some tips today")
}

方法范围之外。您不在onCreate方法之外,实际上是在MainActivity类中编写此代码,因此请将其更改为:

var fixedIncome : Int = 50
var tips : Int = 20
var income : Int = fixedIncome + tips

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    if(tips == 0){
    Log.d("tag", "You have not recieved any tips today")
    }else{
    Log.d("tag", "You have recieved some tips today")
    }
}

或者,初始化并使用onCreate中的所有内容:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    var fixedIncome : Int = 50
    var tips : Int = 20
    var income : Int = fixedIncome + tips

    if(tips == 0){
    Log.d("tag", "You have not recieved any tips today")
    }else{
    Log.d("tag", "You have recieved some tips today")
  }

 }

作为旁注:

因为您正在做var tips : Int = 20并且从不更改tips,所以您可以考虑使用val tips : Int = 20来表示它是一个值,而不是变量。