简体   繁体   English

如何从文件中读取数字并在 java 中对它们执行操作?

[英]How to read numbers from file and take actions on them in java?

this is my file information:这是我的文件信息:

mahdi aspanani 664 22.0 ali moghadasi 675 26.0

I want to read this information from file and count 22.0 + 26.0我想从文件中读取此信息并计数 22.0 + 26.0

how can I do this in java?我怎么能在java中做到这一点?

  1. First, open your file with a Scanner instance.首先,使用 Scanner 实例打开您的文件。
  2. Read each line.阅读每一行。
  3. Split on spaces在空格上拆分
  4. Convert the fourth token to a double.将第四个标记转换为双精度。
  5. Add it to sum.将其添加到总和中。
  6. Continue until no more lines.继续直到没有更多的行。
        Scanner input;
        String myFileName = "......";
        try {
            input = new Scanner(new File(myFileName)); 
            double sum = 0;
            while (input.hasNextLine()) {
                String line = input.nextLine();
                String[] vals = line.split("\\s+");
                sum += Double.parseDouble(vals[3]);
            }
            System.out.println("sum = " + sum);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Assuming you mean the content of the file is structured like this:假设您的意思是文件内容的结构如下:

<string> <string> <int> <summand 1> <string> <string> <int> <summand 2>

and none of the strings contains spaces and both summands are doubles, you can do the following:并且没有一个字符串包含空格并且两个被加数都是双打,您可以执行以下操作:

try(BufferedReader br=new BufferedReader(new FileReader(filename))){
    String[] split=br.readLine().split(" ");
    double result=Double.parseDouble(split[3])+Double.parseDouble(split[7]);
    //do with it whatever you want
}catch(IOException e){
     e.printStackTrace();//or do something else or don't catch it and add it to the signature
}

Don't forget to put the name ofthe file instead of filename .不要忘记输入文件filename而不是filename

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM