文本文件包含随机符号,我想计算数字0-9。
我正在努力弄清楚如何将文本文件读取到数组中,如何正确地将特定数字的出现次数计数到数组中,然后使用方法显示出现次数。
到目前为止,这是我的代码:
// Get the filename.
System.out.print("Enter the filename: ");
String filename = keyboard.nextLine();
// Open the file.
File file = new File(filename);
Scanner inputFile = new Scanner(file);
char [] charMap = new char [1380];
// Read lines from the file until no more are left.
while (inputFile.hasNext())
{
// Read the map.
String map = inputFile.nextLine();
charMap = map.toCharArray();
// Display the map.
System.out.println(charMap);
}
// Close the file.
inputFile.close();
} }
答案 0 :(得分:0)
根据您的示例,这是工作示例,如果您想计算文件中每一行的位数。
// Read lines from the file until no more are left.
while (inputFile.hasNext())
{
// Read the map.
String map = inputFile.nextLine();
charMap = map.toCharArray();
// Display the map.
System.out.println(countNumber(charMap));
}
//方法
private static int countNumber(char[] chars) {
int count = 0;
for (int i=0; i<chars.length; i++) {
if (Character.isDigit(chars[i])) {
count++;
}
}
return count;
}
或者,如果您能以最简单的方式做到这一点,则:1)以字符串形式读取整个文件内容,2)从字符串中构建数组,3)从它们中进行计数,如下所示:
String inputFile = new Scanner(file).useDelimiter("\\z").next();
char[] charMap = inputFile.toCharArray();
System.out.println(countNumber(charMap));