2017-11-13 13 views
0

저는 프로그래밍과 자바에 익숙하지 않지만 열거하고 입력 텍스트 파일을 읽는 프로그램을 만들어야하는 과제가 있습니다. 12 정수가 쓰여져 있고, 내가 만든 정수 배열로 텍스트 파일의 번호를 읽고, 배열을 낮은 값에서 높은 값으로 정렬하는 메서드에 매개 변수로 전달한 다음 정렬 된 배열 번호를 결과물 파일. 출력 파일은 또한 루프를 사용하여 계산되고 정렬 된 정수 목록 끝에 배치 된 모든 정수의 평균을 표시해야합니다.배열로 입력 파일을 읽고, 정렬 한 다음 파일로 출력합니다.

아래는 내가 지금까지 가지고있는 것입니다. 배열을 올바르게 정렬하고 main 함수로 다시 보내는 방법을 알아낼 수 없습니다. 나는 또한 평균을 얻고 산출하는 방법을 명확하지 않다. 누구든지 도와 주시면 감사하겠습니다. 미리 감사드립니다. 당신의 data_array에 읽기와

import java.util.Scanner; 
import java.util.Arrays; 

public class NumberSorter { 

    public static void main(String[] args) throws Exception {  
     double sum = 0;  
     double avg = 0; 
     double total = 0; 
     int i = 0, 
     number = 0; 
     int[] data_array = new int[12]; 
     java.io.File file = new java.io.File("numbers.txt"); 
     Scanner input = new Scanner(file); 

     while(input.hasNext()){ 
      data_array[i] = input.nextInt(); 
      sortArray(data_array); 
      avg = sum/total; 
      java.io.PrintWriter output = new java.io.PrintWriter("dataout.txt"); 
      output.close(); 
     } 
    } 

    public static void sortArray(int[] data_array) 
    { 
     Arrays.sort(data_array); 
    } 
} 

답변

0

귀하의 주요 문제는 당신이 당신의 while 루프 i의 값을 증가 결코 당신이 단지 위치 0으로 때마다 읽을 수 있다는 것입니다. 따라서 매번 배열의 첫 번째 요소를 텍스트 파일의 다음 값으로 덮어 씁니다.

은 단순히 내가 출력을하고이 루프의 외부 전체 separation of concerns 생각을 (정렬 추천 할 것입니다 그리고 data_array[i] = input.nextInt();

아래 i++;를 추가하여 해결할 수 있습니다 참고 : 이상적으로 모든 다른 방법 또는 클래스와 수행 문제에 따라 다르지만 여기서는 예를 들어 main 방법으로 남겨 두겠습니다.)

그래서 따라서 다음 다음 위치로 다음 int를 추가하려고하지만, 현재이는 array를 정렬 바와 같이, while 루프의 외부 sortArray 전화를 이동하는 것이 좋습니다 년대 array는 다른 순서대로 지금 (아마도), 생각하는 곳에 추가하지 않습니다.

또 다른 문제는 dataout 파일에 아무 것도 쓰지 않는다는 것입니다.

파일에 기록하는 데는 여러 가지 방법이 있지만 이것은 하나의 예일뿐입니다.

java.io.FileWriter fr = new java.io.FileWriter("dataout.txt"); 
     BufferedWriter br = new BufferedWriter(fr); 
     try (PrintWriter output = new PrintWriter(br)) { 
      for (int j = 0; j < data_array.length; j++) { 
       System.out.println(data_array[j]); 
       output.write(data_array[j] + "\r\n"); 
      } 
     } 

평균을 계산하여 파일 끝에 추가하면됩니다

하지만 먼저 배열의 모든 숫자의 합을 계산해야합니다.

그래서 다른 루프를 만드는 대신 이전 while 루프에 루프를 추가하고 각 반복마다 값을 추가해야합니다.

sum += data_array[i]; 

당신이 array (즉 고정 된 길이)를 사용하는 것처럼, 당신은 단지 while 루프에 total++;을 추가 할 다른 사용자 total 변수의 값을 얻기 위해 array.length()를 사용하거나 할 수있다.

그러면 avg = sum/total;이 작동합니다.

전체 코드 :

public class NumberSorter { 

    public static void main(String[] args) throws Exception { 
     double sum = 0; 
     double avg = 0; 
     double total = 0; 
     int i = 0; 
     int[] data_array = new int[12]; 
     java.io.File file = new java.io.File("numbers.txt"); 
     Scanner input = new Scanner(file); 

     while (input.hasNext()) { 
      data_array[i] = input.nextInt(); 
      //add to the sum variable to get the total value of all the numbers 
      sum += data_array[i]; 
      total++; 
      //increment the position of 'i' each time 
      i++; 
     } 
     //only sort the array after you have all the elements 
     sortArray(data_array); 

     //gets the average of all elements of the array 
     avg = sum/total; 

     java.io.FileWriter fr = new java.io.FileWriter("dataout.txt"); 
     BufferedWriter br = new BufferedWriter(fr); 
     try (PrintWriter output = new PrintWriter(br)) { 
      for (int j = 0; j < data_array.length; j++) { 
       //write each element plus a new line 
       output.write(data_array[j] + "\r\n"); 
      } 
      //write the average (to two decimal places - plus it doesn't allow 
      //you to write doubles directly anyway) to the file 
      output.write(String.format("%.2f", avg)); 
      output.close(); 
     } 
    } 

    public static void sortArray(int[] data_array) { 
     Arrays.sort(data_array); 
    } 
}