gpt4 book ai didi

java - 如何使用 IndexOf 和子字符串 Java 从字符串中提取多个单词?

转载 作者:行者123 更新时间:2023-11-30 07:49:20 25 4
gpt4 key购买 nike

我有一个通过系统导入的文件,现在我陷入困境。使用 while 循环和 if 语句,并且没有 Split() 方法的帮助,我如何首先使用扫描仪逐行读取文件?其次,我怎样才能将单词一个一个地拉出来,当我拉出一个单词时,一个变量,countWords必须增加一,假设字符串中有5个单词,我需要运行循环5次, countWords 将变为 5。这是我到目前为止的代码,有点蹩脚。

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

关于java - 如何使用 IndexOf 和子字符串 Java 从字符串中提取多个单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33490289/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com