我的Scala代码存在什么问题?求错误排查指导
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 returnnullif there’s no more input left. Callingstr.charAt(0)on anullstring will immediately throw an exception. - Empty String Crash: If
stris an empty string,str.charAt(0)will trigger anIndexOutOfBoundsException. 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 aNumberFormatException.
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 answithfoldLeftto accumulate results immutably (more aligned with Scala’s functional paradigm). - Added
OptionandTryto handle invalid input cases gracefully instead of crashing. - Removed redundant variable declarations.
- Completed the
mainmethod to properly read input, compute the result, and print it. - Added checks for empty/null strings to prevent runtime exceptions.
内容的提问来源于stack exchange,提问作者user3243499

