나는 .txt 인 모든 숫자를 읽을 수 없습니다

프랑코 토레스 :

미안 숫자의 10 수백만이 포함 된 파일을 평균하려고 한 줄에 하나 개의 번호가있다. 나는 두 번을 반환 getAverage ()라는 메서드가 만들었습니다. 이 코드입니다 :

public double promedioDouble() throws IOException
    {
        double adder = 0;
        int counter = 0;
        try{
                file = new FileReader(filePath);
                reader = new BufferedReader(file);
                while(reader.readLine()!=null)
                {
                    adder+=Double.parseDouble(reader.readLine());
                    counter++;
                }

            }
        catch (IOException e) 
        {
              System.out.println("cant read");
        }
        finally {
            if (file != null) file.close();
        }             
        return adder/counter;
    }

나는 카운터의 인쇄를 만들어 그것을 독자가 파일에 포함 된 10 개 수백만 번호를 읽어 어차피 그것은 절반 만 읽어 왜 나를 5.000.000, 난 몰라했다. 나는이 도움을 필요로한다.

racraman :

당신이 전화하는거야 readLine두 번 - 그리고 내 반환되는 라인을 무시하고 while조건을.

대신보십시오 :

            String line;
            while( (line = reader.readLine()) !=null)
            {
                adder+=Double.parseDouble(line);
                counter++;
            }

- 당신은 또한 스트림이 작업을 수행 (대한 필요성을 피하고 시도 -과 - 자원 수 finally:)

    try (Stream<String> stream = Files.lines(Paths.get(fileName))) 
    {
        stream.forEach(s -> {adder+=Double.parseDouble(s); counter++;});

    } catch (IOException e) {
        e.printStackTrace();
    }

추천

출처http://43.154.161.224:23101/article/api/json?id=314073&siteId=1