It's a Cotlin question.

Asked 2 years ago, Updated 2 years ago, 84 views

class MainActivity : AppCompatActivity() {

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

    but1.setOnClickListener(){

        var random: Random? = null
        var number: Int = random!!.nextInt(6)

        when(number){
            1 -> Toast.makeText (this, "1.", Toast.LENGTH_SHORT).show()
            2 -> Toast.makeText (this, "2.", Toast.LENGTH_SHORT).show()
            3 -> Toast.makeText (this, "3.", Toast.LENGTH_SHORT).show()
            4 -> Toast.makeText (this, "4.", Toast.LENGTH_SHORT).show()
            5 -> Toast.makeText (this, "5.", Toast.LENGTH_SHORT).show()
            6 -> Toast.makeText (this, "6.", Toast.LENGTH_SHORT).show()

        }

    }

}

}

I'm trying to create an app that prints out Toast every time I click a button using random class from 1 to 6, but there's an error when I click a button. There is no error on the code, and the app turns off when you click the button on the emulator, is there anything wrong with the code?

For your information, I gave button ID but1 to layout.

kotlin android-studio

2022-09-22 19:27

1 Answers

var random: Random? = null
var number: Int = random!!.nextInt(6)    

random!! <-- This expression means that the variable may be null, but it is not null, so just do it without caring. If you declare random null right above, but it's not null and force it to run, you'll get an error when you run it.


2022-09-22 19:27

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.