简体   繁体   中英

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

I have a file i imported through system, Now i am stuck. Using while loops and if statements, and WITHOUT the help of the Split() method, How could i first, Read the file, line by line with the scanner? Then second how could i pull the words out one by one, As i pull out one word, A variable, countWords has to increase by one, say there is 5 words in a string, I would need to run through the loop 5 times and countWords would become 5. This is the code i have so far, Kind of crappy.

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++;

 }

There is more to my code, however it is just a few calculations commented out. Thanks!

Here is how I would refactor your while loop to correctly extract, print, and count all words in a sentence:

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
    }
}

I tested this code by hard-coding the string fileRead to be your first sentence The cat is black. . I got the following output.

Output:

The
cat
is
black

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM