You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin中如何实现类似Dice随机数生成类的随机字符串生成类

How to Implement a Random String Picker Class in Kotlin (Similar to Your Dice Class)

Let's break down the issues in your current code first, then walk through correct implementations that mirror your Dice class's flexible, configurable design.

Issues in Your Coin Class Code

  1. Kotlin Type Case Sensitivity: The string type in Kotlin is String (uppercase S), not string. Using lowercase will throw compilation errors.
  2. Unused Constructor Parameter: Your Coin class takes a side parameter but never uses it—right now the flip() method hardcodes "H" and "F", which defeats the configurable spirit of your Dice class.
  3. Hardcoded Options: The Dice class uses the input numSides to define its random range, so your string picker should let users pass in their own set of options instead of locking them to fixed values.

Solution 1: Optimized Coin Class (For Coin Flip Scenarios)

This version fixes syntax issues and makes the coin sides configurable (with a default for standard heads/tails):

class Coin(val sides: List<String> = listOf("Heads", "Tails")) {
    fun flip(): String {
        return sides.random()
    }
}

fun main() {
    // Use the default standard coin
    val standardCoin = Coin()
    println("Your coin flip result is ${standardCoin.flip()}!")
    
    // Create a custom trick coin with an extra "edge" option
    val trickCoin = Coin(listOf("H", "T", "Edge"))
    println("Your trick coin flip result is ${trickCoin.flip()}!")
}

Solution 2: Generic Random String Picker (Mirroring Dice's Flexibility)

If you want a reusable class (like how Dice works for any number of sides), this generic picker lets you pass any collection of strings to choose from randomly:

class RandomStringPicker(val options: List<String>) {
    // Optional safety check: Ensure we have at least one option to pick from
    init {
        require(options.isNotEmpty()) { "The options list can't be empty—we need something to select!" }
    }
    
    fun pick(): String {
        return options.random()
    }
}

fun main() {
    // Use it as a coin flip
    val coinPicker = RandomStringPicker(listOf("H", "T"))
    println("Your coin flip result is ${coinPicker.pick()}!")
    
    // Repurpose it for a prize draw
    val prizePicker = RandomStringPicker(listOf("iPhone", "iPad", "AirPods", "Consolation Prize"))
    println("Your prize is ${prizePicker.pick()}!")
}

Key Parallels to Your Dice Class

  • Configurable Input: Just like Dice takes numSides to define its random range, RandomStringPicker takes options to define the pool of possible strings.
  • Single Action Method: pick() mirrors roll()—it's the straightforward method to trigger a random selection.
  • Optional Validation: The init block in RandomStringPicker adds a safety check, similar to how you might want to ensure numSides is a positive number in your Dice class.

内容的提问来源于stack exchange,提问作者Aaditya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 12:57:33