'How to return one of two strings in Kotlin?
So I just recently started learning Kotlin through Google's new course and I learn how to randomly choose a number from a dice. I'm slightly confused about part of it so I tried to make a random coin flip program to help understand it better. I try to use the .random to choose between the two strings but it doesn't work and gives a long error. Here's the code so far:
fun main() {
val coinSide = Coin()
println("You flipped a ${coinSide}")
}
class Coin (){
fun flip() : String {
val head = ("Heads")
val tails = ("Tails")
return (head..tails).random()
}
}
Solution 1:[1]
Google asked you to "Create a Coin class, give it the ability to flip, create an instance of the class and flip some coins". Here's how you can do it:
fun main() {
val my5CentCoin = Coin(5)
println("Your ${my5CentCoin.cent} cent coin flipped ${my5CentCoin.flip()}!")
val my10CentCoin = Coin(10)
println("Your ${my10CentCoin.cent} cent coin flipped ${my10CentCoin.flip()}!")
val my25CentCoin = Coin(25)
println("Your ${my25CentCoin.cent} cent coin flipped ${my25CentCoin.flip()}!")
}
class Coin(val cent: Int) {
fun flip(): String {
val flipSide = listOf("Heads","Tails").random()
return flipSide
}
}
Here's the output:
Your 5 cent coin flipped Heads!
Your 10 cent coin flipped Tails!
Your 25 cent coin flipped Heads!
Solution 2:[2]
I'm sure the OP has found an answer to the question in the comment by now, but for posterity... the ".flip() part of the println statement" calls the flip function. Without it you are just creating an instance of a blank object. Your coin class has no value until the flip() function is ran.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Joshua Combs |
