gpt4 book ai didi

Java Codelab 字母计数器

转载 作者:行者123 更新时间:2023-11-30 07:36:28 25 4
gpt4 key购买 nike

File Letter Counter

编写一个程序,要求用户输入文件名,然后要求用户输入一个字符。程序应该计算并显示该次数文件中出现指定字符。使用记事本或其他文本编辑器创建可用于测试程序的示例文件。

有人可以解释为什么计数不起作用,我总是得到 0 的输出。

import java.util.Scanner; 

public class TESTTEST
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter file name:");

String linestr = sc.nextLine().toUpperCase();
System.out.print(" Enter character to count:");

char ch = sc.next().toUpperCase().charAt(0);

int count = 0;
for(char ch0:linestr.toCharArray()) {
if(ch0 == ch)
count++;
}
System.out.println(" The character " + "'"+ch+"'" + " appears in the file wc4 " + count + " times.");
}
}

最佳答案

这是因为您当前正在检查文件名称中的字符,而不是文件本身。您实际上应该采用完整的文件路径,除非该文件位于同一目录中,在这种情况下您可以只采用名称(因为这是本地路径)。

下面是修改后的代码,允许从文件中读取:

import java.util.*; 

public class TESTTEST
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter file path:");

//This is the path to the file you want to read from
String path = sc.nextLine();
System.out.print(" Enter character to count:");

char ch = sc.next().toUpperCase().charAt(0);

//read all lines into a list
List<String> lines = Files.readAllLines(Paths.get(path), StandardCharsets.UTF_8);
int count = 0;
for(String linestr:lines){
for(char ch0:linestr.toCharArray()) {
if(ch0 == ch)
count++;
}
}
System.out.println(" The character " + "'"+ch+"'" + " appears in the file wc4 " + count + " times.");
}
}

另请查看documentation for Files.readAllLines请注意,此函数不适用于读取大文件。使用ScannerBufferedReader而不是大文件。

关于Java Codelab 字母计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35326799/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com