【问题标题】:How do I convert two different columns from a .csv file to an array?如何将 .csv 文件中的两个不同列转换为数组?
【发布时间】:2015-04-02 19:18:23
【问题描述】:

我正在尝试从 csv 文件中的不同列创建两个不同的数组。 csv 文件有一列用于“月份”,一列用于“温度”。这是我目前所拥有的,但我不知道如何将这些值转换为数组。

public class InputOutput
{
    private double temperature;

    public InputOutput()
    {
        List<String> temperatures = new ArrayList<String>();
        Iterator<String> tempIterator = temperatures.iterator();

    }

    public static double getTemp()
    {
        double tempReading = 0.0;
        try
        {
            String fileName = "C:\\Users\\Joseph\\Downloads\\MNMINPLS.csv";                 //location of MNMINPLS.csv
            File file = new File(fileName);
            Scanner scan = new Scanner(file);                                               //scanner reads file
            while(scan.hasNext())                           //iterator
            {
                String tempData = scan.next();
                String[] nums = tempData.split(",");
                tempReading = Double.parseDouble(nums[3]);

                System.out.println(tempReading);
            }//end while
            scan.close();
        }
        catch(FileNotFoundException e)
        {
            e.printStackTrace();
        }//end try/catch
        return tempReading;
    }//end method getTemp

    public static int getMonth() 
    {
        int m = 0;
        try
        {
            String fileName = "C:\\Users\\Joseph\\Downloads\\MNMINPLS.csv";                 //location of MNMINPLS.csv
            File file = new File(fileName);
            Scanner scan = new Scanner(file);                                               //scanner reads file
            while(scan.hasNext())                       //iterator
            {
                String month = scan.next();
                    if(month == month)
                        m++;
                String[] timeOfYear = month.split(",");
                m = Integer.parseInt(timeOfYear[0]);

                System.out.println(m);
            }
            scan.close();
        }
        catch(FileNotFoundException e)
        {
            e.printStackTrace();
        }//end try/catch
        return m;
    }
}       

【问题讨论】:

  • 您想要数组或数组列表(因为您有一个温度数组列表)?每当您不知道如何使用标准 Java 类时,最好先咨询documentation。您会发现这样做之后,您大部分时间都可以回答自己的问题。提示:ArrayList 有一个 .add() 方法。

标签: java arrays csv


【解决方案1】:
temperatures.add(Double.toString(tempReading));

只需将值添加到 ArrayList。

【讨论】:

    【解决方案2】:

    您只需要读取一次文件

    double[] temperatures=new double[maxsize];
     String[] months=new String[maxsize];
     int index=0;
        while(scan.hasNext())                           //iterator
                {
                    String tempData = scan.next();
                    String[] nums = tempData.split(",");
                    tempReading = Double.parseDouble(nums[3]);
                    monthReading = nums[2]; //or whichever index
                    temperatures[index]=tempReading;
                    months[index]=monthReading;
                    index++
              }
    

    【讨论】:

      【解决方案3】:

      如果我理解正确,您的 &lt;date&gt;,temp 行是这样的:

      4,12,2014,70.3 //12 Apr 2014 weather
      5,1,2014,74.5 //1 May 2014 weather
      6,27,2014,85.8 //27 June 2014 weather
      

      最后你想要的是一个 int 数组 monthsArr,其值为 {4, 5, 6},再加上一个并行双精度数组 tempsArr,其值为 {70.3, 74.5, 85.8}

      首先,使您的temperatures ArrayList 成为该类的成员(将其移至private double temperature 所在的位置),然后添加一个额外的months ArrayList。 将温度设为ArrayList&lt;Double&gt;,将月份设为ArrayList&lt;Integer&gt;

      然后,您可以使用add() 方法将解析后的值添加到相应的ArrayList 中。

      最后,完成解析后,最简单的转换为数组的方法是使用toArray() 方法,如下所示:

      double[] tempsArr = temperatures.toArray(new double[]);
      int[] monthsArr = months.toArray(new int[]);
      

      ArrayList&lt;E&gt; API 规范 (Java SE7) 是 here

      【讨论】:

        【解决方案4】:

        如何读取和解析 CSV 文件?我会使用第三方 CSV 阅读器,比如 CSV 阅读器。可以在here 找到“为什么不编写自己的 CSV 解析器”列表。希望这会有所帮助:):

        import com.opencsv.CSVReader;
        
        import java.io.FileReader;
        import java.util.List;
        import java.util.ArrayList;
        
        CSVReader reader = new CSVReader(
                                new FileReader("C:\\Users\\Joseph\\Downloads\\MNMINPLS.csv"));
        String [] nextLine;
        
        // If you want lists
        List<Integer> months       = new ArrayList<Integer>();
        List<Double>  temperatures = new ArrayList<Double>();
        while (null != (nextLine = reader.readNext())) 
        {
            months.add(
                        Integer.valueOf(nextLine[0]));
            temperatures.add(
                        Double.valueOf(nextLine[1]));
        }
        
        // or if you want your data as an array see http://docs.oracle.com/javase/7/docs/api/java/util/List.html#toArray(T[])
        Integer[] monthsArr = months.toArray(new Integer[0]);
        Double[]  tempsArr  = temperatures.toArray(new Double[0]);
        

        【讨论】:

          猜你喜欢
          • 2020-07-24
          • 2013-02-27
          • 1970-01-01
          • 1970-01-01
          • 2020-05-24
          • 2016-06-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多