2012-09-26 55 views
1

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

我缺少/做错了吗?

回答

4
if (nextWord.size > longestWord) longestWord = nextWord.size; theWord = nextWord; println(theWord + " " + longestWord) 

你不应该写上这样一行多个语句。让我们用多行写出并正确缩进:

if (nextWord.size > longestWord) 
    longestWord = nextWord.size 
theWord = nextWord 
println(theWord + " " + longestWord) 

你现在看到问题了吗?

+0

啊,我明白了。 longestWord的赋值是if语句评估后执行的唯一事情。谢谢! – NickAbbey

+0

在Scala中,阻塞和缩进是否考虑了更好的样式,或者podiluska的回答如下,其中的语句是一种“内联”分号并用卷曲大括号包裹,被认为是更好的样式? – NickAbbey

+0

@NickAbbey不确定,你在这里的意思是“阻塞”或“内联”。就分号而言,我认为不使用它们是普通的Scala风格(虽然我不是专家)。 – sepp2k

0

试着把{}围绕你的if语句替代。

您可以通过以结构化方式格式化代码来避免此类错误 - 始终在代码块周围使用大括号。

if (nextWord.size > longestWord) 
{ 
     longestWord = nextWord.size; 
     theWord = nextWord; 
     println(theWord + " " + longestWord); 
} 

您当前的代码就相当于

if (nextWord.size > longestWord) 
{ 
     longestWord = nextWord.size; 
} 
theWord = nextWord; 
println(theWord + " " + longestWord); 
+2

Scala(和Java)中的标准样式是将大括号放在前一行的末尾。 –

相关问题