我有一个程序,它应该计算指定文件中特定字符的所有实例,例如“A”。我得到它来计算角色,除了它只看一个单词开头的字符。因此,“aa aaa a ba”只算作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);
}
}
答案 0 :(得分:2)
这是因为你只是在比较第一个角色。
//read a char from the file
// THIS : only the first character
char count = inputFile.next().charAt(0);
//count the char if it is the one specified
if (count == countedChar)
{
++sum;
}
你应该循环遍历所有字符,然后如果它与countedChar
相匹配则增加总和,例如..
String str = inputFile.next()
for (int i = 0; i < str.length(); i++) {
char count = str.charAt(i);
// check if it matches the countedChar and then increment.
}
答案 1 :(得分:0)
那是因为你只是在读第一个字符
String word = inputFile.next(); //read a word
int counter = 0;
for(counter=0;counter<word.length();counter++) // traverse through the word
{
char count = word.charAt(i); // ith char
//count the char if it is the one specified
if (count == countedChar)
{
++sum;
}
}
答案 2 :(得分:0)
尝试使用一个变量而不是零,它在类的开头初始化为零,然后为它计数的每个char递增它,所以:
//read a char from the file
char count = inputFile.next().charAt(m);
++m;
//count the char if it is the one specified
if (count == countedChar)
{
++sum;
}
然后在main方法中定义:
int m = 0
答案 3 :(得分:0)
这是因为你正在使用
char count = inputFile.next().charAt(0);
默认情况下,next
会读取,直到它找到空格或数据结尾,所以现在它会读取并返回整个单词。
如果您想要使此方法有效,则需要next
一次只返回一个字符,因此在imputFile
扫描程序中设置分隔符以清空inputFile.useDelimiter("");
之类的字符串。
答案 4 :(得分:0)
while (inputFile.hasNext()) {
String word = inputFile.next();
for (int i = 0; i < word.length(); i++) {
if (word.charAt(i) == countedChar) {
++sum;
}
}
}
答案 5 :(得分:0)
作为替代方案,您可以使用专用于阅读的阅读器:
BufferedReader reader = new BufferedReader(new FileReader(file));
int read;
while((read = reader.read())>0) if (read==countedChar) count++;
reader.close();