读取文件并从字符串和整数打印平均值

时间:2016-04-17 15:15:34

标签: java file io split

我有一个文本文件,每行包含一个名称和一个整数序列,例如

Jules 50 60 40
Ali 45 70 70 90
Emma 45 54

我为我的代码提供了这个但是它不打印平均值我也不确定如何读取整数序列

   public void AverageMarks(String fName, String pname) {

    BufferedReader br = null;
    try{ 
         br = new BufferedReader(new FileReader(fName));
        }catch(FileNotFoundException e){
        System.out.println("Could not find file");
    }

    try{    
        double average = 0;
        double sum = 0;
        String line;

        while((line = br.readLine()) != null){
          String[] lines = line.split(" ");

           if(pname.equals(lines[0])){
                for(int i =0; i<lines.length; i++){
              sum+= Double.parseDouble(lines[i+1]);
            } 
             average = sum / lines.length;
            System.out.println(average);
            System.exit(0);
          }
          else{
              System.out.println(pname + " No such name");
              System.exit(0);
            }
        }

    }catch(IOException e){
        System.out.println("An error has occured");
    }
    finally{
        System.exit(0);
    }
  }

例如,平均值是双倍......

  • AverageMarks("myfile.txt","Jules")应打印50.0
  • AverageMarks("myfile.txt","Ali")应打印68.75
  • AverageMarks("myfile.txt","Neil")应打印Neil No such name

1 个答案:

答案 0 :(得分:1)

问题是,您else循环中不应该while阻止。 else块语句应该不在考虑以确保您已经处理了文件中的所有行,并且不存在这样的名称。 for循环索引也存在问题。它应该从1而不是0开始。试试这个:

public void AverageMarks(String fName, String pname) {

    BufferedReader br = null;
    try{ 
         br = new BufferedReader(new FileReader(fName));
        }catch(FileNotFoundException e){
        System.out.println("Could not find file");
    }

    try{    
        double average = 0;
        double sum = 0;
        String line;

        while((line = br.readLine()) != null){
          String[] lines = line.split(" ");

          if(pname.equals(lines[0])){
            if(lines.length > 1) { // check to calculate average only when there are numbers as well in the line
              for(int i = 1; i<lines.length; i++){ // loop index shold start from 1 as element at index 0 is name
                sum+= Double.parseDouble(lines[i]);
              }

              average = sum / (lines.length - 1);
            }
            System.out.println(average);
            System.exit(0);
          }
        }

        // moved these lines from inside loop, to make sure all the names in the files have been checked
        System.out.println(pname + " No such name");
        System.exit(0);

    }catch(IOException e){
        System.out.println("An error has occured");
    }
    finally{
        System.exit(0);
    }
  }