我的教授正在使用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