以下是我正在使用的代码。输出文件可以正确打印,但不能打印正确数量的字符或大写/小写字母。
public class FileProcessing
{
public static void main(String[] args) throws IOException
{
File file1 = new File("input.txt");
Scanner scanner = new Scanner(file1);
scanner.hasNextLine();
String s = scanner.nextLine();
int length = s.length();
char[] charAnalysis = s.toCharArray();
int lowercase = 0;
int uppercase = 0;
for (char element : charAnalysis)
{
if (Character.isUpperCase(element))
{
uppercase++;
}
else if (Character.isLowerCase(element))
{
lowercase++;
}
}
File file2 = new File("output.txt");
try (PrintStream ps = new PrintStream(file2))
{
ps.println("Number of characters is " + length);
ps.println("Number of lower case letters is " + uppercase);
ps.println("Number of upper case letters is " + lowercase);
}
catch(IOException e)
{
}
}
}
答案 0 :(得分:2)
您的程序正确计算了大写和小写字符。 将输出保存到文件时,您犯了一个错误:
您尝试将大写字母保存为小写字母。
ps.println("Number of **lower case** letters is " + **uppercase**);
ps.println("Number of **upper case** letters is " + **lowercase**);
解决方案是替换变量:
ps.println("Number of lower case letters is " + lowercase);
ps.println("Number of upper case letters is " + uppercase);
重要的是,您只能从文件中读取一行,因此您的程序将仅在第一行中计算字符。
如果要计算每一行,则需要循环读取行,然后计算字符。