我有一个通过系统导入的文件,现在卡住了。使用while循环和if语句,并且没有Split()方法的帮助,我如何首先与扫描器逐行读取文件?然后第二个,我该如何一遍又一遍地提取单词,当我提取出一个单词A变量时,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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句