[英]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.