【问题标题】:Reading Digits/Integer from File in Java用Java从文件中读取数字/整数
【发布时间】:2020-03-12 05:21:14
【问题描述】:

我正在尝试计算文件中的所有整数,但由于.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());
        }
    } 

numbers.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.

【问题讨论】:

  • Scanner input - 现在去阅读Scanner的javadocs

标签: java arrays io


【解决方案1】:

更新

我只是检查您的输入文件。您计算每个数字的方法是完全错误的。您必须将行拆分为 white space 的单词数组并检查该单词是否为数字。


您可以通过FileInputStream 读取您的文件并逐行处理。如果您只想计算数字(多位数字),每行将由white space 拆分为单词,或者您可以将一行转换为字符数组并检查每个字符。

这里有两个类,您需要使用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.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-01
    • 2013-07-08
    • 2018-07-22
    • 1970-01-01
    • 2023-03-20
    • 2012-07-07
    • 2016-05-27
    • 1970-01-01
    相关资源
    最近更新 更多