【发布时间】:2020-10-18 04:48:06
【问题描述】:
我想创建一个从 .txt 文件中随机打印一行的程序。这就是我目前所处的位置,我能找到的唯一其他类似问题是其他语言的。例如,带有random.choice() 操作的Python,我在这个问题中找到了:How to choose a random line from a text file
感谢大家的宝贵时间!
fun main() {
val file = "text.txt"
println(file.random("text.txt")) //This code doesn't work, I'm just illustrating what I was looking to do.
}
我认为有必要进行的修改: 我正在导入的库。
import java.io.FileReader
import kotlin.system.exitProcess
import java.io.FileWriter
import kotlin.random.Random
我学到的更多东西:
有一个函数 RandomAccessFile 用于我想要做的确切目的,但是,我没有找到任何关于如何在 Kotlin 中使用它的好资源。
评论编辑: 我可以从文件中读取,当我这样做时,所有行都会按顺序打印。
1:我知道如何生成随机数,但是我不知道如何将其添加到 .txt 文件中。
2:我尝试使用以下代码添加与其所在行对应的数字,但是,此代码在 i 变量未被理解为现有数字的情况下运行时出错。
下面和粘贴中的代码错误,以确保整洁。 https://pastebin.com/FxFWjv37
fun main() {
var i = 1
println("Please input a value, type DONE when done, READ to print.")
val loop = 0
while (loop < 1) {
var response = readLine()
if (response == "DONE") {
exitProcess(0)
}else if (response== "READ") {
RandomRead()
} else {
WriteToFile(i + response)
i+1
}
}
}
错误:(23, 31) Kotlin:以下函数都不能使用提供的参数调用:
public final operator fun plus(other: Byte): Int defined in kotlin.Int
public final operator fun plus(other: Double): Double定义在kotlin.Int
public final operator fun plus(other: Float):在kotlin.Int中定义的浮点数
public final operator fun plus(other: Int): Int defined in kotlin.Int
public final operator fun plus(other: Long): Long 定义在 kotlin.Int
public final operator fun plus(other: Short): Int defined in kotlin.Int
我也尝试过:
fun main() {
println("Please input a value, type DONE when done, READ to print.")
val loop = 0
while (loop < 1) {
var response = readLine()
if (response == "DONE") {
exitProcess(0)
}else if (response== "READ") {
RandomRead()
} else {
WriteToFile(response)
}
}
}
fun WriteToFile(str: String?) {
var i = 0
try {
var fo=FileWriter("test.txt")
fo.write(i + " " + str + "\n")
fo.close()
i+1
}catch (ex:Exception){
println(ex.message)
}
}
错误:(37, 20) Kotlin:以下函数都不能使用提供的参数调用:
public final operator fun plus(other: Byte): Int defined in kotlin.Int
public final operator fun plus(other: Double): Double定义在kotlin.Int
public final operator fun plus(other: Float):在kotlin.Int中定义的浮点数
public final operator fun plus(other: Int): Int defined in kotlin.Int
public final operator fun plus(other: Long): Long 定义在 kotlin.Int
public final operator fun plus(other: Short): Int defined in kotlin.Int
【问题讨论】:
-
你能逐行读取文本文件吗?你知道如何生成随机整数吗?
-
查看
readLines扩展函数以获取File对象,它会为您提供List<String>。那么你只需要随机选择一条线。