除了第一个和最后一个,我如何总结数组中的所有项目

时间:2016-04-07 17:11:52

标签: java

我是新编码我想知道我的错误是什么。要求转换为double的图表添加到数组然后对数组中除frist和last之外的所有项目求和。来自文本文件

这是文本文件:

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

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 sum = 0;
     double answer=0;
     double array[] = new double[1000];
     while(sc.hasNext()){
       Arrays.sort(array);
       double b=sc.nextDouble();  
     } 
     contestant++;
     answer = answer + sum;
     System.out.println("For Competitor #" + contestant + ", the average is " + (answer/8) );
   }
  }
}

我想打印像:

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

2 个答案:

答案 0 :(得分:1)

在上面列出的代码中,您永远不会更改变量sum&amp;的值。回答,所以它们将始终为0,如初始化语句中那样。

答案 1 :(得分:0)

根据我对您的问题的理解,您希望丢弃竞争对手的最佳和最差结果,然后计算剩余数字的平均值。目前,您没有将每个竞争对手的值写入您排序的阵列中。你快到了。

你会发现使用ArrayList和ArrayList比使用字符串和双精度数组更容易。

例如,要读入文件中的行:

File file = new File( "C:\\temp_Name\\DataGym.in.txt" );

ArrayList<String> lines = new ArrayList<String>();

// Use try() like this to automatically close the file when finished
try( Scanner scanner = new Scanner( file ) ) {
   while( scanner.hasNext() )
      lines.add( scanner.nextLine() );
}
catch( Exception ex ) {
   // TODO: handle a failure to read your input file gracefully...
}

然后处理每个竞争对手的结果:

for( String line : lines ) {
   Scanner scanner = new Scanner(line);
   ArrayList<Double> values = new ArrayList<Double>();
   while( scanner.hasNextDouble() )
      values.add( scanner.nextDouble() );

   Collections.sort(values);
   double sum = 0;

   // Sum starting from the second element, and finishing before the last
   for( int index = 1; index < values.size() - 1; ++index )
      sum += values.get(index);

   // TODO: What do you want to do if there are two or fewer values?
   double mean = sum / values.size() - 2;

   // Do whatever you want to log this contestants results...
}