java - 在Java中从文件中读取数字/整数

标签 java arrays io

我试图计算文件中的所有整数,但由于 .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读取文件并逐行处理它。如果您只想计算数字(具有多个数字),则每行将通过空格分割为单词,或者您可以将行转换为字符数组并检查每个字符。

这里有两个类,您需要使用FileInputStreamBufferReader

该示例基于您的代码(计数数字)

// 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/

相关文章:

java - 如何将字节数组写入流程构建器的 OutputStream (Java)

java - 从build.gradle从Java类访问变量

java - 在多次调用的函数中对数组进行一次排序

java - 如何将数据库记录列表(通过 Hibernate 检索)显示到 Struts 2 中的 JSP 页面?

arrays - 使用数组参数时出现递归 SQL Lvl 1 错误

arrays - 在 PowerShell 中调整字节数组图像的大小

c# - Directory.EnumerateFiles 与 Directory.GetFiles 之间有什么区别?

java - 两次获得完全相同的对象引用的机会有多大

javascript - 如何搜索和替换对象文字数组中的值

linux - 有没有办法在没有底层操作系统的情况下驱动当今的计算机 NIC?