Java 我需要帮助修复代码中的一个逻辑错误,该错误应该是查找.txt文件中某些字母出现的次数
我有一个程序,可以找到一个.txt文件中出现四个字母的次数,但它找不到正确的字母数。导致此问题的原因是什么,如何解决?为什么我的程序只计算一些字母而忽略其他字母Java 我需要帮助修复代码中的一个逻辑错误,该错误应该是查找.txt文件中某些字母出现的次数,java,logic,Java,Logic,我有一个程序,可以找到一个.txt文件中出现四个字母的次数,但它找不到正确的字母数。导致此问题的原因是什么,如何解决?为什么我的程序只计算一些字母而忽略其他字母 import java.util.Scanner; 导入java.io.File; 导入java.io.IOException; 导入java.io.BufferedReader; 导入java.io.FileNotFoundException; 公共类计数{ 公共静态void main(字符串[]args)引发FileNotFound
import java.util.Scanner;
导入java.io.File;
导入java.io.IOException;
导入java.io.BufferedReader;
导入java.io.FileNotFoundException;
公共类计数{
公共静态void main(字符串[]args)引发FileNotFoundException{
字符串短语;//一个字符串
int countBlank;//短语中的空格数
int length;//短语的长度
char ch;//字符串中的单个字符
int countA;
整数计数;
整数计数;
int countT;
java.io.File File=新的java.io.File(“counting.txt”);
扫描仪内嵌=新扫描仪(文件);
扫描仪扫描=新扫描仪(System.in);
短语=infle.nextLine();
长度=短语。长度();
//初始化计数
while(true){
if(短语.equalsIgnoreCase(“退出”)){
打破
}否则{
countBlank=0;
countA=0;
计数=0;
计数=0;
countT=0;
for(int i=0;i
尝试使用此代码片段,在扫描仪实例化后插入
String everything = ""; //Makes a blank string
while(infile.hasNext())
everything += infile.next(); //Fills the string with everything from the text file
everything = everything.toLowerCase(); //converts the string to lowercase, so you don't have to compare multiple cases
for(char c : everything.toCharArray())//converts everything to an array of characters, runs a for each on it with c as a character
if(Character.isWhiteSpace(c)) //if the character is a space, increase the countBlank var
countBlank++;
else
switch (c) //switch you had to increase the count of a letter
{
case 'a':
countA++;
break;
case 'e':
countE++;
break;
case 's':
countS++;
break;
case 't':
countT++;
break;
}
如果您需要我为您解释任何代码,请告诉我。我将使用
StringUtils
中的countMatches
方法。
请看一下文档
您的代码可以像这样重新编写-
String phrase = "";
while(inFile.hasNext()) {
phrase += inFile.nextLine();
}
phrase = phrase.toLowerCase();
countBlank = StringUtils.countMatches(phrase, " ");
countA = StringUtils.countMatches(phrase, "a");
countE = StringUtils.countMatches(phrase, "e");
countS = StringUtils.countMatches(phrase, "s");
countT = StringUtils.countMatches(phrase, "t");
你的实际产出是多少?你得到的结果是否比预期的少?你得到0了吗?我得到的比我预期的要少。我应该得到3个a,7个e,4个s,3个t,这就是我得到的空格数:6个a的数目:0个e的数目:4个s的数目:0个t的数目:2从正确缩进代码开始。完成后,将很容易识别错误。好的。现在代码缩进了:程序实际读取了多少行,即执行了多少次
infle.nextLine()
?您不觉得奇怪吗,读取该行的代码不在while循环中?while循环进行了多少次迭代?你不觉得奇怪吗,不管这行包含什么内容,你最后总是调用break代码>,结束循环?当我用此代码替换当前代码时,是否需要删除代码中的任何内容?@user318803:在不了解您的代码不正确的原因以及您粘贴的代码的实际用途的情况下,不要用其他人的代码替换您的代码。那样做你什么也学不到。阅读我的评论,并尝试思考代码的作用。在大脑中或在一张纸上一步一步地执行代码。学习需要时间。你的代码几乎是正确的。你只要想想我在评论中强调的内容。@user318803我实际上有点错误。我把扫描仪infle
和scan
搞混了,这可能会把你搞糊涂。很抱歉。