如何在没有拆分方法或使用数组的情况下将字符串拆分为单词?

时间:2015-11-02 23:05:25

标签: java string

我最近得到了一些功课让我做了这个奇怪的任务。老师希望我们将各种句子分成单词。老师把这些放在通过扫描仪导入的文件中。

老师希望我们用这些词来计算长度,每次迭代循环时单词的数量应该随着单词的数量而增加。

文件总是以字符“#”结尾,这就是我开始的地方。

这是我到目前为止所拥有的

  class Assignmentfive
  {
 private static final String String = null;

 public static void main(String[] args) throws FileNotFoundException
 {
    Scanner scan = new Scanner(new File("asgn5data.txt"));

    String fileRead = " ";
    System.out.print(fileRead);
    double educationLevel = 0;
    double wordCount = 0;

   while (fileRead != "#")
   {
     fileRead = scan.nextLine();    

     int firstIndex = fileRead.indexOf(" ");
     String strA = fileRead.substring(0,firstIndex);
     System.out.print(strA);
     int strLength = strA.length();
     wordCount++;   
     }

现在,底部有更多内容,这是我的计算,我无法弄清楚如何从文件中逐字逐句提取

任何提示?

Thanks``

1 个答案:

答案 0 :(得分:0)

永远不要使用String(该引用标识,而不是您想要的==类型的值标识Object)来测试.equals平等。您可以使用{{3>}构造函数构造一个新的Scanner,它可以生成从指定字符串扫描的值。此外,您永远不会close d Scanner }(由File支持,这是资源泄漏)。您可以明确致电close,但我更喜欢Scanner(String)。像,

try (Scanner scan = new Scanner(new File("asgn5data.txt"))) {
  int wordCount = 0;
  while (true) {
    String fileRead = scan.nextLine();
    if (fileRead.equals("#")) {
      break;
    }
    Scanner wordScanner = new Scanner(fileRead);
    while (wordScanner.hasNext()) {
      String word = wordScanner.next();
      System.out.println(word);
      int wordLength = word.length();
      wordCount++;
    }
  }
} catch (Exception e) {
  e.printStackTrace();
}
相关问题