2016-03-23 25 views
0

Her satır için, bir metin dosyasında aynı satırdaki sayıların ortalamasını bulmaya çalışıyorum.Metin dosyasından ortalama bul

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 

ben gibi bir şey yazdırmak istiyorum: Bu metin dosyası ise Örneğin,

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

Bu benim kodudur.

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); 
    } 
    } 
} 

O Burada sorunu karmaşık hale bitti

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

, bu ödevini yapmak cevap (ve belki çok geniş bir sorudur ?) –

cevap

1

yazdırır. Snippet'i takip etmek, burada başarmaya çalıştığınız şeyi elde etmenizi sağlamak için yeterlidir. İşte

kod parçacığı geçerli:

Çıktı
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)); 
    } 
} 

:

Kodunuza hata ayıklama veya analizinizi göndermek için gereken
For Competitor #1, the average is 5.69 
For Competitor #2, the average is 0.0 
For Competitor #3, the average is 1.0 
İlgili konular