在java中计算特定字符,但我的程序只读取单词中的第一个字符
我有一个程序,可以计算指定文件中特定字符(如“a”)的所有实例。我让它数一数字符,除了它只看单词开头的字符。所以“aaba”只能算作4个“a”,而不是7个。我已经尽我所能地发表了评论,所以我的思路很清晰,但我对编程相当陌生,所以如果我不清楚,我提前道歉
import java.util.Scanner;
import java.io.*;
public class Charcounter
{
public static void main(String[] args) throws IOException
{
//accumulator
int sum = 0;
Scanner kb = new Scanner(System.in);
//get filename and character to be counted from user
System.out.println("Enter the name of a file: ");
String filename = kb.nextLine();
System.out.println("Enter the name of the character to be counted: ");
char countedChar = kb.next().charAt(0);
//check if file exists
File file = new File(filename);
if (!file.exists())
{
System.out.println("File specified not found.");
System.exit(0);
}
//open file for reading
Scanner inputFile = new Scanner(file);
//read file and count number of specified characters
while (inputFile.hasNext())
{
//read a char from the file
char count = inputFile.next().charAt(0);
//count the char if it is the one specified
if (count == countedChar)
{
++sum;
}
}
//close file
inputFile.close();
//display number of the specified char
System.out.println("The number of the character '" + countedChar + "' is : " + sum);
}
}
# 1 楼答案
这是因为你只是在比较第一个角色
您应该循环遍历所有字符,然后如果与
countedChar
匹配,则增加总和,类似# 2 楼答案
尝试使用一个变量,而不是在类的开头初始化为零的零,然后对它计数的每个字符递增,因此:
然后在主要方法中定义:
# 3 楼答案
那是因为你只是在读第一个字符
# 4 楼答案
作为替代方案,您可以使用专用于字符读取的读卡器:
# 5 楼答案
# 6 楼答案
这是因为你正在使用
默认情况下
next
将一直读取,直到找到空白或数据结尾,所以现在它读取并返回整个单词如果你想让这种方法起作用,你需要
next
一次只返回一个字符,所以在imputFile
扫描器中设置分隔符为空字符串,比如inputFile.useDelimiter("");