2016-10-24 2 views
0

입력 파일의 데이터를 사용하여 다른 문서에 쓰고 해당 파일에서 평균 및 표준 편차를 계산하도록 지정되었습니다. 내 코드가 올바르게 컴파일되고 (Dr.Java에 따라) 문제가 발생하지만 출력 파일에 출력을 제공하지 않습니다. 내가 문제 영역이라고 생각하는 코드가 첨부되어있다. 루프 이전에 파일을 읽거나 사용 된 루프 일 수 있습니다. 그 장소가 오류의 장소인지 누가 알 수 있습니까?입력 파일 읽기 및 코드 출력 안 함

// Create a File object passing it the filename 
    File readFile = new File(filename); 
    // Create a Scanner object passing File object 
    Scanner inputFile = new Scanner(filename); 
    // Perform a priming read to read the first line of the file; 
    line = inputFile.nextLine(); 
    while (inputFile.hasNext()) //create a loop that continues until you are at the end of the file 
    { 
    while(Double.parseDouble(line) != -1) 
     { 
     sum += Double.parseDouble(line); //convert the line into a double value and add the value to the sum 
     count++; //increment the counter 
     line = inputFile.nextLine(); //read a new line from the file 
     } 
     mean = sum/count; 
    } 
    inputFile.close(); 

출력 파일 코드 :

// Create a FileWriter object using "OutputFileProcess.txt" 
    File file = new File("OutputFileProcess.txt"); 
    FileWriter fw = new FileWriter(file); 
    // Create a PrintWriter object passing the FileWriter object 
     PrintWriter outputFile = new PrintWriter("OutputFileProcess.txt"); 
    // Print the results to the output file 
     outputFile.println(mean); 
     outputFile.println(stdDev); 
    // Close the output file 
     outputFile.close(); 

코드는 두 개의 루프를 필요로 하나는 NED 때까지 계속하고, 하나는 텍스트 파일에 어떤 음수를 제외 할 수 있습니다. 나 자신을 소개해야한다. 나는 조이다.

+1

디버거를 사용하는 법을 배워야합니다. – ControlAltDel

+0

출력 파일에 어디에 쓰고 있습니까? 게시 한 코드는 읽기 용입니다. – BCartolo

+0

방금 ​​출력 파일 코드를 추가했습니다. 오류가 한 영역에만 있다고 생각하기 때문에 코드를 너무 많이 게시하고 싶지 않습니다. –

답변

0

이것은 문제의 핵심은 아니지만 while 루프 중 하나는 사용되지 않습니다. 내부 상태

Double.parseDouble(line) != -1 

거짓지면

는 외부 루프 동안 line의 값과 루프 더이상 입력되지 않을 때, 내부를 변경하지 않을 것이다. 그래서 전체 알고리즘은 처음 -1에서 멈 춥니 다.

또한 ==와 복식을 비교하기 때문에, 구문 분석하고 (그들은 모두있는 경우) 정수로 값을 비교 고려해야한다

while (inputFile.hasNext()) 
{ 
    final String line = inputFile.nextLine(); 
    final double lineAsDouble = Double.parseDouble(line); 
    if (lineAsDouble != -1D) { 
     sum += lineAsDouble; 
     count++; 
    } 
} 
final double mean = (double) sum/(double) count; 

이 다운 될 작성하는 더 좋은 방법은 항상 위험하다.