我最近做了一些作业,让我完成了这个奇怪的任务。老师要我们把不同的句子拆成单词。老师已将这些内容放入通过扫描仪导入的文件中。
老师要我们用这些单词来计算长度,单词的数量应该随着循环的每次迭代而增加。
文件总是以字符“#”结尾,所以这就是我开始的地方。
这是我到目前为止所拥有的
class Assignmentfive
{
private static final String String = null;
public static void main(String[] args) throws FileNotFoundException
{
Scanner scan = new Scanner(new File("asgn5data.txt"));
String fileRead = " ";
System.out.print(fileRead);
double educationLevel = 0;
double wordCount = 0;
while (fileRead != "#")
{
fileRead = scan.nextLine();
int firstIndex = fileRead.indexOf(" ");
String strA = fileRead.substring(0,firstIndex);
System.out.print(strA);
int strLength = strA.length();
wordCount++;
}
现在,底部还有更多,这是我的计算,我不知道如何从文件中逐字提取
有什么建议吗?
谢谢``
最佳答案
永远不要测试 String
与 ==
的相等性(这是引用标识,而不是与您想要 .equals
的 Object
类型的值标识)。您可以使用 Scanner(String)
构造函数,它构造一个新的Scanner
,生成从指定字符串扫描的值。此外,您永远不会关闭
您的Scanner
(由File
支持,这是资源泄漏)。您可以显式调用 close
,但我更喜欢 try-with-resources
Statement 。比如,
try (Scanner scan = new Scanner(new File("asgn5data.txt"))) {
int wordCount = 0;
while (true) {
String fileRead = scan.nextLine();
if (fileRead.equals("#")) {
break;
}
Scanner wordScanner = new Scanner(fileRead);
while (wordScanner.hasNext()) {
String word = wordScanner.next();
System.out.println(word);
int wordLength = word.length();
wordCount++;
}
}
} catch (Exception e) {
e.printStackTrace();
}
关于java - 如何在不使用 split 方法或使用数组的情况下将字符串拆分为单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33488643/