我目前正在尝试编写一个循环遍历文本文件的程序,以查找第一个超过 9 个字符的单词。
我曾认为我首先需要获得一个完整的单词,因此为此我应该使用 for 循环遍历文件中的每个项目,并将其添加到 currentWord 变量中。
其次,获得这个词/字符串后,我会执行第二步 - 将其长度与目标('THRESHOLD')长度 9 进行比较。如果它更大,那么我找到了第一个词长度大于或等于 10,并会在一个句子中返回它。否则,循环会继续迭代吗?
这是我目前所拥有的:
// Write a program that finds the first word in Alice In Wonderland
// that is longer than a given number of characters.
import java.util.Scanner;
import java.io.FileReader;
import java.io.FileNotFoundException;
public class LearningLoops {
public static void main(String[] args) throws java.io.FileNotFoundException
{
Scanner in = new Scanner(new FileReader("aliceInWonderland.txt"));
String longWord = "";
boolean found = false;
final int THRESHOLD = 9;
int i;
String currentWord;
for (i = 0; in.charAt(i) != " "; i++) {
currentWord = currentWord + i;
i++;
}
while (in != null) {
if (currentWord.length() > THRESHOLD) {
longWord = currentWord;
}
System.out.println("The first long word is: " + longWord);
}
}
}
这是正确的方法吗?我被困住了,非常感谢任何帮助。
最佳答案
一个非常简单的解决方案是这样的:
BufferedReader br = new BufferedReader(new FileReader("aliceInWonderland.txt"));
String line;
while ((line = br.readLine()) != null) {
String[] words = line.split(" ");
for (String word : words) {
if (word.length() >= 9) {
return word;
}
}
}
关于java - 如何在特定长度的文本文件中找到第一个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21910623/