java 如何使用方法从文本文件中返回某个字母的金额

ljsrvy3e  于 2023-03-06  发布在  Java
关注(0)|答案(3)|浏览(121)

假设我有一个文本文件,里面充满了随机的单词或字母,我需要能够增加一个字母被看到的次数。举个例子,我试图找到字母'a'。当程序编译并返回一个数字时,这个数字可能太高或太低,这与我正在寻找的某个字母的数量有关。改变我的代码,我如何解决这个问题?
哦!我应该提到的是,我发送这段代码的人希望它以具有方法的形式构造,而Problem 9只有参数(File,file),必须构造成方法的形式

package module4labs;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.InputMismatchException;

public class Module4Labs {
    public static void main(String[] args) {
        new Module4Labs();
    }
    
    public Module4Labs() {
        double problemSolution = Problem9(new File("Problem9.txt"));
                System.out.println(problemSolution);        
    }

//Problem 9: Find 'a'
public int Problem9(File file) {
    int counter =0;
    try {
    Scanner input = new Scanner(file);
    ArrayList<String> list = new ArrayList<String>();
    while(input.hasNext()) {
        list.add(input.next());
    }
    
    for (int x=0; x<list.size()-1;x++) {
        if (list.subList(x,x+1).equals('a'));
        counter++;
    }
    input.close();
 } catch (FileNotFoundException e) {
    System.out.println(file + "File Not Found.");
    }
 return counter;

}

目前,我从Eclipse收到一个警告,说“equals()的参数类型不太可能:char似乎与List无关”
不确定如何继续

n3schb8v

n3schb8v1#

  • 我发送这段代码的人希望它看起来像这样 * 不,他们不希望。这段代码违反了Java中的几个编码约定;Problem9是一个糟糕的、没有描述性的方法名。您正在计算char的出现次数。不要硬编码char-将其传递给方法,并给予方法一个合适的名称,如countChar。迭代文件的行,然后迭代行的内容,查找char。接下来,不要计算结果并在构造函数中打印出来,我会把countChar设为静态的,但是假设你必须示例化你的类,我会在main中这样做,然后调用这个方法,比如,
public static void main(String[] args) {
    Module4Labs m4l = new Module4Labs();
    double problemSolution = m4l.countChar(new File("Problem9.txt"), 'a');
    System.out.println(problemSolution);
}

public int countChar(File file, char ch) {
    int counter = 0;
    // This is a try-with-Resources, don't hard code input.close();
    try (Scanner input = new Scanner(file)) {
        while (input.hasNextLine()) {
            String line = input.nextLine();
            for (int i = 0; i < line.length(); i++) {
                if (line.charAt(i) == ch) {
                    counter++;
                }
            }
        }
    } catch (FileNotFoundException e) {
        System.out.println(file + " File Not Found.");
    }
    return counter;
}
wi3ka0sx

wi3ka0sx2#

我们也可以使用java.nio.file包来完成这个任务。

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

public class CharacterFrequency {
    private String str;

    public CharacterFrequency(File file) {
        try {
            this.str = Files.readString(file.toPath());
        } catch (IOException e) {
            System.err.println(e);
        }
    }

    public int getFrequency(char a) {
        int frequency = 0;
        for (char b : str.toCharArray()) {
            if (a == b) {
                frequency++;
            }
        }
        return frequency;
    }

    public void showFrequency(char a) {
        int frequency = getFrequency(a);
        System.out.printf("The character %c appears %d times\n", a, frequency);
    }

    public static void main(String[] args) {
        if (args.length < 1) {
            System.out.println("Usage: java CharacterFrequency.java path/to/file");
            return;
        }
        File f = new File(args[0]);
        CharacterFrequency cf = new CharacterFrequency(f);
        cf.showFrequency('a');
        cf.showFrequency('z');
        cf.showFrequency('g');
        cf.showFrequency('p');
    }
}

我创建了一个example.txt文件,它包含以下内容:

The soccer player scored a goal.

我将文件example.txt保存到与CharacterFrequency.java相同的目录中。
然后我运行命令:

% java CharacterFrequency.java example.txt
The character a appears 3 times
The character z appears 0 times
The character g appears 1 times
The character p appears 1 times
qvsjd97n

qvsjd97n3#

其他代码示例使用逐行阅读和/或创建字符串。这是不必要的-只需读取char s:

import java.io.Reader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class CharacterFrequency {

    public static int getFrequency(Path inputPath, char c) throws IOException {
        int frequency = 0;
        int buf = -1;
        try (Reader in = Files.newBufferedReader(inputPath)) {
            while ((buf = in.read()) > -1) {
                if (buf == c) {
                    frequency++;
                }
            }
        }
        return frequency;
    }

    public static void main(String[] args) {
        try {
            if (args.length < 2) {
                System.err.println("Usage: java CharacterFrequency <path/to/file> <character to find>");
                System.exit(1);
            }
            Path inputPath = Path.of(args[0]);
            char c = args[1].charAt(0);
            System.out.printf("Frequency of character %c in file %s is %d%n", c, inputPath.toString(),
                    CharacterFrequency.getFrequency(inputPath, c));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

相关问题