簡體   English   中英

除了第一個和最后一個之外,我如何對數組中的所有項目求和

[英]How I can sum all items in array except first and 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

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

在上面列出的代碼中,您永遠不會更改變量 sum 和 answer 的值,因此它們將始終為 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...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM