计算字母出现 [英] Counting letter occurrence

查看:171
本文介绍了计算字母出现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

程序需要计算并显示指定的charector出现在文本文件中的次数。



目前总数为零。我不是,如果我应该使用不同的循环,我也尝试使用for循环。

  //保持用户输入并且
字符串fileName; //保存文件名
字符串; //在文件中搜索的字母
int total = 0; //保存文件中的字符总数


//从用户获取文件和字符的名称
fileName = JOptionPane.showInputDialog(请输入文件名称:);
letter = JOptionPane.showInputDialog(请输入包含在字符串中的字母);


//打开文件读取
文件file = new File(fileName);
扫描仪输入文件=新扫描仪(文件); //为文件读取声明新的扫描器对象


//将累加器设置为零
int count = 0;

if(inputFile.nextLine()。equalsIgnoreCase(letter)){

count ++; //添加字母出现

total + = count; //将字母出现添加到总共

$ / code $ / $ p

解决方案

  BufferedReader reader = new BufferedReader(new FileReader(somefile.txt)); 
int ch;
char charToSearch ='a';
int counter = 0; ((ch = reader.read())!= -1){
if(charToSearch ==(char)ch){
counter ++;
}
};
reader.close();

System.out.println(counter);

这有什么帮助吗?


The program needs to count and display the number of times that the specified charector appears in the text file.

Currently turning up zero for the total. I'm not if I should be using a different loop, I've also tried using a 'for' loop.

// Hold user input and sum
String fileName;    // Holds the name of the file
String letter;      // Letter to search for in the file
int total = 0;      // Holds the total number of characters in the file


// Get the name of the file and character from the user
fileName = JOptionPane.showInputDialog("Please enter the name of a file:");
letter = JOptionPane.showInputDialog("Please enter a letter contained in the string");


// Open the file for reading
File file = new File(fileName);         
Scanner inputFile = new Scanner(file);  // Declare new scanner object for file reading


// Set accumulator to zero
int count = 0;

if (inputFile.nextLine().equalsIgnoreCase(letter)) {                                

    count++;          // add letter occurrence

    total += count;   // add the letter occurrence to the total
}

解决方案

    BufferedReader reader = new BufferedReader(new FileReader("somefile.txt"));
    int ch;
    char charToSearch='a';
    int counter=0;
    while((ch=reader.read()) != -1) {
        if(charToSearch == (char)ch) {
            counter++;
        }
    };
    reader.close();

    System.out.println(counter);

Is this of any help?

这篇关于计算字母出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆