Java 文件信件计数器错误
编写一个程序,要求用户输入文件名,然后要求用户输入字符。程序应计算并显示指定字符在文件中出现的次数Java 文件信件计数器错误,java,loops,Java,Loops,编写一个程序,要求用户输入文件名,然后要求用户输入字符。程序应计算并显示指定字符在文件中出现的次数 我的问题是第24行和第25行的长度和字符有错误,我不知道该怎么做才能让程序运行 import java.util.Scanner; import java.io.*; public class challenge6 { public static void main(String[] args) throws Exception { String string;
我的问题是第24行和第25行的长度和字符有错误,我不知道该怎么做才能让程序运行
import java.util.Scanner;
import java.io.*;
public class challenge6 {
public static void main(String[] args) throws Exception {
String string;
char character;
int count = 0;
File file = new File("./file.txt");
Scanner input = new Scanner(file);
input.hasNextLine();
while (input.hasNextLine())
System.out.println(input.nextLine());
System.out.println("enter name of a char");
character = input.next().charAt(0);
for(int i=0; i < input.length(); i++)
{ if(input.charAt(i) == character)
count++;
}
System.out.println(count);}}
一种更简单的方法是利用String::replace方法将char替换为blank,并检查前后的字符串长度。您还需要在整个文件中循环
File f = new File("c:/tmp/file.txt");
Scanner input = new Scanner(f);
int count = 0;
String charToFind = "a";
while (input.hasNextLine()) {
String line = input.nextLine();
int len = line.length();
line = line.replace(charToFind, "");
count += len - line.length();
}
System.out.format("There were %d occurrences found%n", count);
input.close();
你有问题吗?那么,问题是什么?input.nextLine只读取一行,甚至没有将该行保存在变量中。input.lenght-是否存在此方法?第24行和第25行的长度和字符错误,我不确定如何使程序运行。p.s。只是学习循环,希望有人能向我解释这个代码,并修复它。先谢谢你。