我试图计算文件中的所有整数,但由于 .toCharArray();
和 .length()
; ,我不断收到错误。它们都是“找不到符号 - 方法 toCharArray()”?
public static void main(String[] args){
try{
FileReader f = new FileReader(("numbers.txt")); //replace this to exact location where you store numbers.txt in computer
Scanner input = new Scanner(f);
char[] count = input.toCharArray();
int num = 0;
for (int i =0; i<input.length(); i++){
if(Character.isDigit(count[i])){
num++;
}
System.out.println("There are "+num+" numbers in the file.");
}
} catch(Exception s){
System.out.println(s.getMessage());
}
}
数字.txt:
8 96 54 25
104 19
112 86 73
16 30 112 57
2 26 64 83
65
36 1
25
18 111
56 104 8 36 87
我的预期输出是这样的:
> There are 28 numbers in the file.
最佳答案
更新
我只是检查你的输入文件。您计算每个数字的方法是完全错误的。您必须通过空格将行拆分为单词数组,并检查该单词是否是数字。
<小时/>您可以通过FileInputStream
读取文件并逐行处理它。如果您只想计算数字(具有多个数字),则每行将通过空格分割为单词,或者您可以将行转换为字符数组并检查每个字符。
这里有两个类,您需要使用FileInputStream
和BufferReader
。
该示例基于您的代码(计数数字)
// Open the file
FileInputStream fstream = new FileInputStream("textfile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String line = null;
int count = 0;
//Read File Line By Line
while ((line = br.readLine()) != null) {
for(Character c: line.toCharArray()) {
//check if the c is a digit and increase count
}
}
//Close the input stream
fstream.close();
//return count or print it out.
关于java - 在Java中从文件中读取数字/整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60648046/