我的教授正在使用Horstmann的書「Scala for the impatient」來教給我們Scala,我們的作業練習之一直接來自於這本書;第4章,鍛鍊2.爲什麼我得到不正確的字符串長度值?
我們預計在電子書文本格式閱讀,教授也有指定的輸入文件應該是「白鯨」,可以免費從加滕伯格項目位置:http://www.gutenberg.org/ebooks/2701.txt.utf-8
只要計算單詞的實例,我的代碼就可以工作。不過,他還補充道,我們必須將輸出格式化爲兩列,文字左對齊,右對齊。爲此,我確定了本書中最長的單詞,以便能夠確定「單詞」列的寬度。但是,我得到的字符串長度的值是錯誤的。事實上,它告訴我所有的字符串都是相同的長度。 「一個」被報告爲長度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
surfbeaten 26
海灘26
和26
然後26
跳水26
下降26
到26
我缺少/做錯了嗎?
啊,我明白了。 longestWord的賦值是if語句評估後執行的唯一事情。謝謝! – NickAbbey
在Scala中,阻塞和縮進是否考慮了更好的樣式,或者podiluska的回答如下,其中的語句是一種「內聯」分號並用捲曲大括號包裹,被認爲是更好的樣式? – NickAbbey
@NickAbbey不確定,你在這裏的意思是「阻塞」或「內聯」。就分號而言,我認爲不使用它們是普通的Scala風格(雖然我不是專家)。 – sepp2k