簡體   English   中英

如何使用IndexOf和substring Java從字符串中提取多個單詞?

[英]How to Extract Multiple words from a string using IndexOf and substring Java?

我有一個通過系統導入的文件,現在卡住了。 使用while循環和if語句,並且沒有Split()方法的幫助,我如何首先與掃描器逐行讀取文件? 然后第二個,我該如何一個個地拔出單詞,當我拔出一個單詞時,一個變量,countWords必須加一,說一個字符串中有5個單詞,我需要遍歷循環5次,然后countWords將變為5。這是我到目前為止的代碼,有點Kin腳。

import java.util.Scanner;
import java.io.*;

class Assignmentfive
{
private static final String String = null;

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

int educationLevel = 0;
String fileRead = "";
int wordCount = 0;

while (scan.hasNext() && !fileRead.contains("."))
{
  fileRead = scan.nextLine();

  int index = fileRead.indexOf(" ");
  String strA = fileRead.substring(index);

  System.out.print(strA);
  wordCount++;

 }

我的代碼有更多內容,但是僅注釋掉了一些計算。 謝謝!

這是我重構您的while循環以正確提取,打印和計算句子中所有單詞的方式:

while (scan.hasNext()) {
    int wordCount = 0;
    int numChars = 0;
    fileRead = scan.nextLine();

    // Note: I add an extra space at the end of the input sentence
    //       so that the while loop will pick up on the last word.
    if (fileRead.charAt(fileRead.length() - 1) == '.') {
        fileRead = fileRead.substring(0, fileRead.length() - 1) + " ";
    }
    else {
        fileRead = fileRead + " ";
    }
    int index = fileRead.indexOf(" ");
    do {
        String strA = fileRead.substring(0, index);
        System.out.print(strA + " ");
        fileRead = fileRead.substring(index+1, fileRead.length());
        index = fileRead.indexOf(" ");
        wordCount++;
        numChars += strA.length();
    } while (index != -1);

    // here is your computation.
    if (wordCount > 0) {
        double result = (double)numChars / wordCount;  // average length of words
        result = Math.pow(result, 2.0);                // square the average
        result = wordCount * result;                   // multiply by number of words
        System.out.println(result);                    // output this number
    }
}

我通過硬編碼字符串fileRead來測試此代碼,這是您的第一句話The cat is black. 我得到以下輸出。

輸出:

The
cat
is
black

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM