将文本文件中的数字读入Java中的ArrayList

时间:2013-10-13 03:36:22

标签: java arrays arraylist

有人能告诉我如何做这类事情的基本准则吗?你会使用数组或ArrayList,为什么?我在网上找到的任何其他东西都太复杂了,无法理解我的Java使用经验。该文件是一个简单的文本文件,每行有七个十进制值,并包含三行。这是我到目前为止所做的,我只是测试它,看看我是否正确地做了ArrayList。它不断打印一个只有两个括号的空ArrayList。

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;

public class SalesAnalysis 
{
    public static void main (String[] args) throws FileNotFoundException
    {

        Scanner salesDataFile = new Scanner(new File("SalesData.txt"));

        ArrayList<Double> salesData = new ArrayList<Double>();

        while(salesDataFile.hasNextDouble())
        {
            salesData.add(salesDataFile.nextDouble());
        }
        salesDataFile.close();

        System.out.println(salesData);

    }
}

4 个答案:

答案 0 :(得分:5)

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;

public class SalesAnalysis
{
    public static void main (String[] args) throws FileNotFoundException
    {

        Scanner salesDataFile = new Scanner(new File("SalesData.txt"));

        ArrayList<Double> salesData = new ArrayList<Double>();

        while(salesDataFile.hasNextLine()){
            String line = salesDataFile.nextLine();

            Scanner scanner = new Scanner(line);
            scanner.useDelimiter(",");
            while(scanner.hasNextDouble()){
                salesData.add(scanner.nextDouble());
            }
            scanner.close();
        }

        salesDataFile.close();

        System.out.println(salesData);
    }
}

从文件中读取行,然后为每个文件使用扫描程序获取双倍。

对于每行,您可以为每一行创建列表,例如:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;

public class SalesAnalysis
{
    public static void main (String[] args) throws FileNotFoundException
    {

        Scanner salesDataFile = new Scanner(new File("SalesData.txt"));

        while(salesDataFile.hasNextLine()){
            String line = salesDataFile.nextLine();

            ArrayList<Double> salesData = new ArrayList<Double>();

            Scanner scanner = new Scanner(line);
            scanner.useDelimiter(",");
            while(scanner.hasNextDouble()){
                salesData.add(scanner.nextDouble());
            }
            scanner.close();

            System.out.println(salesData);
        }

        salesDataFile.close();

    }
}

当您在第一个while()循环中获得每行值时,您可以使用line做任何事情。

        // number of values in file
        int totalNumValues = 0;
        // total sum
        double totalSum = 0;

        while(salesDataFile.hasNextLine()){
            String line = salesDataFile.nextLine();

            ArrayList<Double> salesData = new ArrayList<Double>();

            // total values in this line
            int numValuesInLine = 0;
            // sum in this line
            double sumLine = 0;

            Scanner scanner = new Scanner(line);
            scanner.useDelimiter(",");
            while(scanner.hasNextDouble()){
                  double value = scanner.nextDouble();
                  sumLine = sumLine + value;
                  numValuesInLine++;
                  totalNumValues++;
                  totalSum = totalSum + value;
            }
            scanner.close();

            System.out.println(salesData);
        }

答案 1 :(得分:1)

我会做这样的事情:

    Scanner salesDataFile = new Scanner(new File("SalesData.txt"));

    ArrayList<ArrayList< double > > salesData = new ArrayList<>();

    while(salesDataFile.hasNextLine() )
    {
        String stringOfNumbers[] = salesDataFile.nextLine().split(",");
        ArrayList< double > aux = new ArrayList<>( stringOfNumbers.length );
        for( int i = 0; i < stringOfNumbers.length; ++i )
           aux.get(i) = Double.parseDouble( stringOfNumbers[i] );
        //... Perform your row calculations ...
        salesData.add( aux );
    }
    salesDataFile.close();

    System.out.println(salesData);

答案 2 :(得分:0)

正如@Justin Jasmann所说,你有逗号分隔的值,所以从技术上来说它们不仅仅是double值,为什么不将它们作为String读取,然后在用逗号后用Double.parseDouble(String s)解析它们通过在每一行使用string.split(",");来分离值。

答案 3 :(得分:0)

这就是你要找的东西,

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;


public class FileRead {


    public static void main(String args[])
    {
        try{
            // Open the file that is the first 
            FileInputStream fstream = new FileInputStream("textfile.txt");

            // Use DataInputStream to read binary NOT text.
            BufferedReader br = new BufferedReader(new InputStreamReader(fstream));

            String strLine;
            List<Double> saleNumbers= new ArrayList<Double>();

            //Read File Line By Line
            while ((strLine = br.readLine()) != null)   {
                // Add number from file to list 
                saleNumbers.add( parseDecimal(strLine)); 
            }
            //Close the input stream
            in.close();

            System.out.println(saleNumbers);
        }catch (Exception e){
            e.printStackTrace();
        }
    }



    public static double parseDecimal(String input) throws NullPointerException, ParseException{
          if(input == null){
            throw new NullPointerException();
          }

          input = input.trim();

          NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.US);
          ParsePosition parsePosition = new ParsePosition(0);
          Number number = numberFormat.parse(input, parsePosition);

          if(parsePosition.getIndex() != input.length()){
            throw new ParseException("Invalid input", parsePosition.getIndex());
          }

          return number.doubleValue();
        }
}