Home > Mobile >  Random answer Android studio Kotlin
Random answer Android studio Kotlin

Time:12-10

I'm a beginner and I wanted to make a code that will print "yes" or "no" on random when the button is clicked. (Using kotlin) here's my code package com.example.calculator

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
import android.view.View

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

        fun buttonPressed(view: View){
            val randomword = Random. ("yes" or "no")
            textView.text = randomword
        }
    }
}

CodePudding user response:

Have a look at the Random class for the things you can generate randomly. You can produce different types from the range of all their possible values, or you can provide a range yourself (e.g. between this Int and that Int). Then you can use those values for useful things, like generating a random index, that kind of thing.

Since you have two values here, you might just want to use Random.nextBoolean() to pick between them:

val randomWord = if (Random.nextBoolean()) "yes" else "no"

So basically that nextBoolean() call evaluates to true or false, and the if condition checks that, and returns one of those two strings. Easy enough, right?


But another thing Kotlin has is the random function on its collections. Basically if you have a collection (list, array, map etc) you can call random() on it to get a random item. This is better than trying to generate an index and then get that item (although there might be cases where you want to do that too)

So you can create a collection of responses, and pick one at random:

val responses = listOf("yes", "no")
val randomWord = responses.random()

CodePudding user response:

to get a random item ("yes" or "no" in your case), you can do

val options = listOf("yes", "no")
val randomWord = options.random()
textView.text = randomWord

and then you may put the above code in an onClickListener for a button in your activity / fragment using viewBinding or findViewById to reference both the textView and the button

CodePudding user response:

You can try something like this:

fun buttonPressed(view: View) {
    val randomInt = (0..1).random()
    if (randomInt == 0) {
        textView.text = "yes"
    } else {
        textView.text = "no"
    }
}
  • Related