需要帮助从Java中的文本文件获取数据我需要找到最高价格以及与该价格相关的数据

问题描述

编写一个程序(AvocadoMining.java),该程序具有以下几个字段和三种方法

     size:int,the number of lines in a file.

     prices: double[]

     totalVolumes:double[]

     regions: String[]

   + AvocadoMining(fileName:String)

它读取文件,将文件中的行数分配给字段大小,然后为价格,totalVolumes,区域创建多个数组。

    +findMax():void

   The method finds out the maximum average price during the year,and then prints the price,the total volumes and the region associated with the price.

      +findTotal(String regionName):double

    The method finds out and returns the total of the total volumes for a given region during  the year.

我正在使用findMax()方法,但是在获取代码中的所有数据时遇到了麻烦。 这是我到目前为止的工作

    import java.util.Scanner;
    import java.io.*;
    public class AvocadoMining
    {
       private int size=0;
       private String[] region;
       private double[] price;
       private double[] totalVolumes;




   public AvacadoMining(String fileName) throws IOException
   {   
     File file=new File(fileName);
     Scanner inputF = new Scanner(file);
  
     while(inputF.hasNextLine())
     {
      String str=inputF.nextLine();
      size++;
  
     }

  
     inputF=new Scanner(file);
     region = new String[size];
     price = new double[size];
     totalVolumes=new double[size];
     int index=0;
     while(inputF.hasNextLine())
     {
       String[] tokens = inputF.nextLine().split(",");
       price[index]=Double.parseDouble(tokens[2]);
       totalVolumes[index]=Double.parseDouble(tokens[3]);
       region[index]=tokens[13].trim();
       index++;
     
  
     } 
  
   }   
  
     public void findMax() throws IOException
     {
       double maximum = price[0];
       for(int i=0;i<price.length;i++)
       {
         if(maximum<price[i])
           maximum = price[i];
        
       }
     
     
     
       String line ="Price: $.2f"+maximum + " Total Volume: "+ 
       totalVolumes[price.indexOf(maximum)] +"Region: " + 
       region[price.indexOf(maximum)]; 
  
  
  }

}

如果我尝试编译,则会在字符串行中出现价格找不到符号错误

解决方法

indexOf不是数组上的方法。您必须自己编写。在现实生活中的编码(用于美元或眼球)中,您不会使用数组,而会使用具有indexOf函数的List,但这听起来像是作业,因此您可能被“锁定”在数组中。您可以使用for循环编写indexOf。

,

如下所示更改您的indexOf行,

String line = "Price: $.2f" + maximum + " Total Volume: " + totalVolumes[indexOf(price,maximum)] + "Region: " + region[indexOf(price,maximum)];

然后,添加以下方法,

public int indexOf(double arr[],double t) 
{ 
    int len = arr.length; 
    return IntStream.range(0,len) 
        .filter(i -> t == arr[i]) 
        .findFirst() // first occurrence 
        .orElse(-1); // No element found 
}