为什么我的字符串长度值不正确?

时间:2012-09-26 15:14:39

标签: string scala

我的教授正在使用Horstmann的书“Scala for the greatient”教我们Scala,我们的一项功课练习直接来自本书。第4章,练习2.

我们需要阅读电子书中的文本格式,教授已指定输入文件应为“Moby Dick”,可从Guttenberg项目免费获取:http://www.gutenberg.org/ebooks/2701.txt.utf-8

就计算单词的实例而言,我的代码有效。但是,他已经添加了一个要求,即我们必须将输出格式化为两列,单词左对齐,计数右对齐。为此,我确定书中最长的单词,以便我可以计算“单词”列的宽度。但是,我得到的字符串长度的值是错误的。事实上,它告诉我所有字符串都是相同的长度。 “a”被报告为长度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个字符!

以下是输出内容的一小部分示例:

husks 26

on 26

26

surfbeaten 26

海滩26

和26

然后26

潜水26

下来26

进入26

我错过了什么/做错了什么?

2 个答案:

答案 0 :(得分: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)

你现在看到问题吗?

答案 1 :(得分: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);