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

我的Scala代码存在什么问题?求错误排查指导

Issues in Your Scala Program & Fixes

Let's walk through the problems in your code step by step, plus some idiomatic Scala tweaks to make it more robust:

1. Incomplete main Method

Your main function cuts off at stdin.re... — it’s missing critical code to read the input value for n, call your getval method, and output the final result. Right now, this code won’t compile or run properly.

2. Redundant Variable Declaration

In getval, you declare var i = 0; but never actually use it. The i in your for(i <- 1 to n) loop is a separate, immutable variable (implicitly a val) created for each iteration. You can safely delete that unused var i line.

3. Input Handling Vulnerabilities

  • Null Pointer Crash: stdin.readLine() can return null if there’s no more input left. Calling str.charAt(0) on a null string will immediately throw an exception.
  • Empty String Crash: If str is an empty string, str.charAt(0) will trigger an IndexOutOfBoundsException. You need to check for empty strings before accessing their characters.
  • Unvalidated Integer Parsing: When converting the second input line to an integer with trim.toInt, if the input isn’t a valid number, this will throw a NumberFormatException.

4. Imperative Style (Non-Idiomatic Scala)

Your code uses var for ans and a for loop with side effects, which works but isn’t the most Scala-idiomatic approach. We can refactor this to use a functional style with foldLeft to avoid mutable variables entirely.

Fixed & Optimized Code Example

Here’s a revised version addressing all the above issues:

import scala.io.StdIn
import scala.util.Try

object Solution {
  def getval(n: Int): Long = {
    (1 to n).foldLeft(0L) { (acc, _) =>
      // Handle null/empty input safely for the string line
      val str = Option(StdIn.readLine()).getOrElse("")
      // Parse integer input safely, default to 0 if invalid
      val z = Try(StdIn.readLine().trim.toInt).getOrElse(0)

      if (str.nonEmpty && str.charAt(0) == 'h') {
        if (z > 0) acc + 1 else acc
      } else {
        if (z > acc) acc + 2 else acc
      }
    }
  }

  def main(args: Array[String]): Unit = {
    // Read n safely, default to 0 if input is invalid
    val n = Try(StdIn.readLine().trim.toInt).getOrElse(0)
    val result = getval(n)
    println(result)
  }
}

Key Improvements:

  • Replaced mutable var ans with foldLeft to accumulate results immutably (more aligned with Scala’s functional paradigm).
  • Added Option and Try to handle invalid input cases gracefully instead of crashing.
  • Removed redundant variable declarations.
  • Completed the main method to properly read input, compute the result, and print it.
  • Added checks for empty/null strings to prevent runtime exceptions.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:24:47