【发布时间】:2026-01-13 21:20:02
【问题描述】:
我一直在尝试从文件中读取输入并对其字符进行分类。打印文本文件中有多少个字符是大写字母、小写字母、数字、空格和其他内容。所以我一直在处理我的代码,但遇到了两个问题。
当我尝试关闭我的扫描仪时,我遇到了 java.lang.IllegalStateException:扫描仪已关闭。此外,我的代码产生了一个无限循环,但我已经看了好几个小时,但我不知道出了什么问题。我是 Java 的初学者,所以我还没有了解 hashmap 或 Buffered Readers。谢谢你的帮助。
这是我的代码:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Characters
{
public static void main(String[] args) throws FileNotFoundException
{
Scanner console = new Scanner(System.in);
System.out.print("Input file: ");
String inputFileName = console.next();
Scanner in = new Scanner(new File(inputFileName));
while(in.hasNextLine())
{
String line = in.nextLine();
int len = line.length();
int uppercase = 0 ;
int lowercase = 0;
int digits = 0;
int whitespace = 0;
int other = 0;
for ( int i = 0 ; i < len ; i++)
{
char c = line.charAt(i);
if (Character.isLowerCase(c))
{
lowercase++;
}
else if (Character.isUpperCase(c))
{
uppercase++;
}
else if (Character.isDigit(c))
{
digits++;
}
else if (Character.isWhitespace(c))
{
whitespace++;
}
else
other++;
}
System.out.println("Uppercase: " + uppercase);
System.out.println("Lowercase: " + lowercase);
System.out.println("Digits: " + digits);
System.out.println("Whitespace: " + whitespace);
System.out.println("Other: " + other);
in.close();
}
}
}
【问题讨论】:
-
假设您将
in.close()移到while循环之外。
标签: java string character java.util.scanner