随机化列表

发布于 2024-10-19 10:52:31 字数 613 浏览 0 评论 0原文

我编写了一个函数来从单词列表中随机选择一个单词。这是我的代码。 但它不能选择一个单词,也不能打印。请告诉我我的代码有什么问题。

def long(a: Int, b: Int): String = {
    var a = 5
    var b = 100
    for (i <- args(1)){
        if (i > a && i < b){
            val rand = new Random(System.currentTimeMillis())
            val random_index = rand.nextInt(new_sun .length)
            val result = new_sun(random_index)
            var guess = println("_ " * result.length)
            }
        else{
            println("You have to input the word with length of 5 < 100")
            }
        return i.toString
        }
}

I wrote a function to choose one word randomly from a lists of words. Here my code.
But it cannot choose one word and cannot print. Please tell me what's wrong with my code.

def long(a: Int, b: Int): String = {
    var a = 5
    var b = 100
    for (i <- args(1)){
        if (i > a && i < b){
            val rand = new Random(System.currentTimeMillis())
            val random_index = rand.nextInt(new_sun .length)
            val result = new_sun(random_index)
            var guess = println("_ " * result.length)
            }
        else{
            println("You have to input the word with length of 5 < 100")
            }
        return i.toString
        }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

无法言说的痛 2024-10-26 10:52:31

这里有很多错误,以至于很难知道从哪里开始。一次取一个片段:

def long

真的,令人难以置信的糟糕方法的名称!

def long(a: Int, b: Int): String = {
  var a = 5
  var b = 100

您将 ab 作为参数,然后立即隐藏名称以创建变量。这些参数没有什么用。

for (i <- args(1)){
    if (i > a && i < b){
        ...
        }
    else{
        ...
        }
    ...
    }

这不遵循任何公认的范围嵌套模式,在块的左大括号之前留一个空格也是一个很好的做法。更糟糕的是,for 块的右大括号对齐为看起来像 else 子句的右大括号。这是产生不可维护代码的有保证的方法。我是所谓的“一个真正的括号样式”的倡导者,您的代码格式如下:

for (i <- args(1)) {
    if (i > a && i < b) {
        val rand = new Random(System.currentTimeMillis())
        val random_index = rand.nextInt(new_sun .length)
        val result = new_sun(random_index)
        var guess = println("_ " * result.length)
    } else {
        println("You have to input the word with length of 5 < 100")
    }
    return i.toString
}

继续前进...

for (i <- args(1))

什么是 args(1),它来自哪里?它必须是一个 Option 或某种要在 for 理解中使用的集合,并且其内容必须与 ab 的类型相同>我>一个&&我< b 比较有效。所以我假设 args(1) 返回一个 Option[Int] ,集合似乎不太可能。

val random_index = rand.nextInt(new_sun .length)
val result = new_sun(random_index)

同样的问题。 new_sun 是什么以及它来自哪里。这个名字什么也没告诉我。 new_sun .length 中的空间看起来也很奇怪。

for (i <- args(1)) {
  if (i > a && i < b) {

更好的写法是:

for (i <- args(1) if i > a && i < b) {

或者

args(1) filter (a to b contains _) map { i =>

但遗憾的是,你不能这样做,因为尽管存在保护条件,但值 i 仍被用作返回值。

这也提醒我:

var a = 5
var b = 100
...
if (i > a && i < b) ...
else println("You have to input the word with length of 5 < 100")

这是检查 5 5 5 5 5 5 <我< 100,或者换句话说,6 <= i <= 99。检查与错误消息不匹配。

var guess = println("_ " * result.length)

println 返回Unit。绝对没有可能的理由将此返回值分配给从未使用过的变量。

return i.toString

Scala 中很少需要 return 语句,其中计算的最终表达式将成为返回值。但您不能简单地删除该关键字,因为它会与其他问题相互作用并会停止代码编译。


通常,您希望编写代码,以便 if/else 块、for 推导式和其他此类构造不会产生副作用(例如调用 println) 。相反,您应该尝试使这些块计算为 String,然后将计算出的字符串传递给方法末尾的 println

您还需要更加了解您拥有哪些变量、它们来自哪里以及它们的名称包含多少信息。

并注意你的语法/布局/格式。程序员们为了更少的事情而以宗教方式进行斗争。

There's a lot gone wrong here, so much that it's difficult knowing where to start. Taking one fragment at a time:

def long

Really, unbelievably bad name for a method!

def long(a: Int, b: Int): String = {
  var a = 5
  var b = 100

You're taking a and b as parameters, then immediately shadowing the names to create vars. Those parameters are useless.

for (i <- args(1)){
    if (i > a && i < b){
        ...
        }
    else{
        ...
        }
    ...
    }

This doesn't follow any recognised pattern for nesting of scope, it's also good practice to leave a space before the opening brace of a block. Worse still, the closing brace for the for block is aligned to look like the closing brace for the else clause. This is a guaranteed way to produce unmaintainable code. I'm an advocate of the so-called "one true bracket style", which you have your code formatted like this:

for (i <- args(1)) {
    if (i > a && i < b) {
        val rand = new Random(System.currentTimeMillis())
        val random_index = rand.nextInt(new_sun .length)
        val result = new_sun(random_index)
        var guess = println("_ " * result.length)
    } else {
        println("You have to input the word with length of 5 < 100")
    }
    return i.toString
}

Moving onward...

for (i <- args(1))

What is args(1), where does it come from? It must be an Option or some sort of collection to be used in a for-comprehension, and its contents must be of the same type as a and b for the i > a && i < b comparison to be valid. So I'm assuming that args(1) returns an Option[Int], a collection seems unlikely.

val random_index = rand.nextInt(new_sun .length)
val result = new_sun(random_index)

Same question. What is new_sun and where does it come from. The name tells me nothing. The space in new_sun .length is also very odd looking.

for (i <- args(1)) {
  if (i > a && i < b) {

is better written:

for (i <- args(1) if i > a && i < b) {

or even

args(1) filter (a to b contains _) map { i =>

But sadly, you can't do that, as the value i is used as the return value in spite of the guard condition.

Which also reminds me:

var a = 5
var b = 100
...
if (i > a && i < b) ...
else println("You have to input the word with length of 5 < 100")

This is checking that 5 < i < 100, or 6 <= i <= 99 in other words. The check doesn't match the error message.

var guess = println("_ " * result.length)

println returns Unit. There is absolutely no possible reason to assign this return value to a variable that is never used.

return i.toString

return statements are rarely needed in Scala, where the final expression evaluated will become the return value. You can't simply delete the keyword though, as it interacts with the other problems and would stop your code compiling.


Generally, you want to write your code so that if/else blocks, for-comprehensions, and other such constructs don't perform side-effects (such as calling println). Instead, you should try and make these blocks evaluate to a String and then pass this evaluated String to println at the end of your method.

You also need to be much more aware of what variables you have, where they come from, and how informative their names are.

and pay attention to your syntax/layout/formatting. Programmers have fought religious ways over less..

九歌凝 2024-10-26 10:52:31

那么,为什么不简单地编写类似的代码来随机选择 List[String] 中的一个 String 呢?

def randomString(liste: List[String]) =
  util.Random.shuffle(liste).head

然后您可以创建另一个函数来在屏幕上打印结果

Well, why not simply write something like that to choose randomly a String in a List[String]?

def randomString(liste: List[String]) =
  util.Random.shuffle(liste).head

You could then create another function to print the result on screen

荭秂 2024-10-26 10:52:31

您的 println 不会尝试打印结果。尝试:(

println("result: " + result)

注意“+”是正确的字符串连接运算符,而不是“*”)

每次在内循环中重新创建 rand 也是不必要且低效的。

Your println doesn't attempt to print the result. Try:

println("result: " + result)

(note '+' is the correct string concatenation operator, not '*')

It is also unnecessary and inefficient to recreate rand each time in the inner loop.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文