私の教授は Horstmann の本 "Scala for the impatient" を使って Scala を教えています。第 4 章、演習 2。
eBook はテキスト形式で読むことが期待されています。教授は、入力ファイルは「Moby Dick」にする必要があると指定しています。これは、次の Guttenberg プロジェクトから無料で入手できます。 txt.utf-8
単語のインスタンスをカウントする限り、私のコードは機能します。ただし、彼は、出力を 2 つの 2 列にフォーマットし、単語を左揃えにし、カウントを右揃えにする必要があるという要件を追加しました。そうするために、「単語」列の幅を把握できるように、本の中で最も長い単語を特定しています。ただし、文字列の長さについて取得している値は間違っています。実際、すべての文字列が同じ長さであることがわかります。"a" は、"Whale"、"Ishmael" などと同様に、長さ 26 として報告されています...
コードは次のとおりです。
object Chapter4Exercise2 extends App {
//for sorting
import util.Sorting._
//grab the file
val inputFile = new java.util.Scanner(new java.io.File("moby.txt"))
//create a mutable map where key/values == word/count
val wordMap = collection.mutable.Map[String, Int]() withDefault (_ => 0)
//for formatting output (later), the longest word length is relevant
var longestWord = 0
var theWord: String = ""
//start reading each word in the input file
while (inputFile hasNext) {
//grab the next word for processing, convert it to lower case, trim spaces and punctuation
var nextWord = inputFile.next().toLowerCase().trim().filter(Character.isLetter(_))
//if it's the longest word, update both theWord and longestWord
if (nextWord.size > longestWord) longestWord = nextWord.size; theWord = nextWord; println(theWord + " " + longestWord)
//update the map value for the key with same value as nextWord
wordMap(nextWord) += 1
}
println("Longest word is " + theWord + " at " + longestWord + " Characters")
}
これらの行の出力:
if (nextWord.size > longestWord) longestWord = nextWord.size; theWord = nextWord; println(theWord + " " + longestWord)
と
println("Longest word is " + theWord + " at " + longestWord + " Characters")
途方もないです。入力ファイルのすべての単語が 26 文字の長さであることがわかります。
出力される内容の小さなサンプルを次に示します。
殻 26
26日
26
波打たれた 26
ビーチ 26
そして26
それから 26
ダイビング 26
ダウン 26
26に
私は何が欠けていますか/間違っていますか?