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
- Kotlin Type Case Sensitivity: The string type in Kotlin is
String(uppercase S), notstring. Using lowercase will throw compilation errors. - Unused Constructor Parameter: Your
Coinclass takes asideparameter but never uses it—right now theflip()method hardcodes"H"and"F", which defeats the configurable spirit of yourDiceclass. - Hardcoded Options: The
Diceclass uses the inputnumSidesto 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
DicetakesnumSidesto define its random range,RandomStringPickertakesoptionsto define the pool of possible strings. - Single Action Method:
pick()mirrorsroll()—it's the straightforward method to trigger a random selection. - Optional Validation: The
initblock inRandomStringPickeradds a safety check, similar to how you might want to ensurenumSidesis a positive number in yourDiceclass.
内容的提问来源于stack exchange,提问作者Aaditya
相关产品推荐
相关产品推荐

