如何使用IndexOf和substring Java从字符串中提取多个单词?
我有一个通过系统导入的文件,现在我卡住了。使用while循环和if语句,在没有Split()方法帮助的情况下,如何首先使用扫描仪逐行读取文件?第二,我怎么能一个一个地把单词拉出来,当我拉出来一个单词,一个变量,countWords必须增加一个,假设一个字符串中有5个单词,我需要在循环中运行5次,countWords就会变成5。 这是我到目前为止的代码,有点糟糕如何使用IndexOf和substring Java从字符串中提取多个单词?,java,string,substring,indexof,Java,String,Substring,Indexof,我有一个通过系统导入的文件,现在我卡住了。使用while循环和if语句,在没有Split()方法帮助的情况下,如何首先使用扫描仪逐行读取文件?第二,我怎么能一个一个地把单词拉出来,当我拉出来一个单词,一个变量,countWords必须增加一个,假设一个字符串中有5个单词,我需要在循环中运行5次,countWords就会变成5。 这是我到目前为止的代码,有点糟糕 import java.util.Scanner; import java.io.*; class Assignmentfive {
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
如果您不能使用
String.split()
,是否允许您使用标记器?不幸的是,这也是否定的。老师说“他们不会教你编程”,我认为你的思路是对的。您可以使用String.indexOf()
查找单词的每一个结尾,然后将该单词的子字符串去掉。因此,创建一个名为String.indexOf()的新行?或者使用我目前必须找到的每个单词的结尾?请格式化您的代码。对于仅读取行,除非需要使用扫描仪
,否则更改为BufferedReader
。扫描仪是一个野兽,性能方面。因为一行可以包含多个单词,所以你需要使用这个方法。这太完美了!现在,我如何使它只查看文件中的第一行,然后进行所有计算,然后转到第二行?您的外部,而循环已经在逐行通过输入文件。如果你只想把每个句子中的每个单词都打印出来,并记下所有单词的总数,那么你就完成了。如果你有其他要求,让我知道,我会尽量解决他们。我必须从一个句子,在他们自己的行打印的话。得到该句子中单词的平均长度,将平均值平方,然后将平均值乘以该句子中的单词数。然后对file.Wow中的每个句子重复。你太棒了。你是人间的神。非常感谢你,伙计。我会花很多时间分析你的代码,这样我可以从中学习。再次感谢你,伙计。我在计算中添加了一个double
cast,q.v.更新的代码。除此之外,它看起来还不错。