2016-03-23 11 views
0

Ich versuche, den Durchschnitt der Zahlen in derselben Zeile in einer Textdatei für jede Zeile zu finden. Dies ist mein CodeMittelwert aus Textdatei finden

For Competitor #1, the average is 5.8625 
For Competitor #2, the average is 0.0000 
For Competitor #3, the average is 1.0000 

: Zum Beispiel, wenn dies die Textdatei ist:

8.7 6.5 0.1 3.2 5.7 9.9 8.3 6.5 6.5 1.5 
0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 
1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 

ich wie etwas drucken möchte.

import java.io.*; 
import java.util.*; 
import java.text.*; 
public class BaseClass 
{ 
    public static void main(String args[]) throws IOException 
{ 
    NumberFormat fmt = NumberFormat.getNumberInstance(); 
    fmt.setMinimumFractionDigits(4); 
    fmt.setMaximumFractionDigits(4); 
    Scanner sf = new Scanner(new File("C:\\temp_Name\\DataGym.in.txt")); 
    int maxIndx = -1; 
    String text[] = new String[1000]; 

    while (sf.hasNext()) { 
     maxIndx++; 
     text[maxIndx] = sf.nextLine(); 
    } 
    sf.close(); 
    int contestant = 0; 

    for (int j = 0; j <= maxIndx; j++) { 
     Scanner sc = new Scanner(text[j]); 
     double scoreAverage = 0; 
     double a = 0; 
     double array[] = new double[1000]; 
     contestant++; 
     if (j <= 10) { 
      a += sc.nextDouble(); 
      array[j] += a; 
     } else { 
      Arrays.sort(array); 
      int i = 0; 
      while (i < 10) { 
       scoreAverage += array[i]; 
       i++; 
      } 
     } 

      String s = fmt.format(scoreAverage); 
      double d = Double.parseDouble(s); 
     System.out.println("For Competitor #" + contestant + ", the average is " + d); 
    } 
    } 
} 

Er druckt

For the Competitor #1, the average is 0.0 
For the Competitor #2, the average is 0.0 
For the Competitor #3, the average is 0.0 
+0

Sie müssen Ihren Code debuggen oder Ihre Analyse zu veröffentlichen, dies zu weit gefasst ist eine Frage zu beantworten (und vielleicht machen Sie Ihre Hausaufgaben ?) –

Antwort

1

Sie sind über das Problem hier zu verkomplizieren. Der folgende Ausschnitt reicht aus, um das zu erreichen, was Sie hier erreichen wollen. Hier

ist der Code-Schnipsel:

public static void main (String[] args) throws Exception 
{ 
    Scanner in = new Scanner(new File("C:\\temp_Name\\DataGym.in.txt")); 
    int counter = 0; 
    String line = null; 
    while(in.hasNext()) { 
     line = in.nextLine(); 
     double sum = 0; 
     String[] splits = line.split(" "); 
     for(String s : splits) { 
      sum += Double.parseDouble(s); 
     } 
     System.out.println("For Competitor #" + (++counter) 
          + ", the average is " + (sum/splits.length)); 
    } 
} 

Ausgang:

For Competitor #1, the average is 5.69 
For Competitor #2, the average is 0.0 
For Competitor #3, the average is 1.0