Read Double From a .txt File into an Array List

java read text file into array of strings
java read text file into array scanner
reading a file into an array of objects java
java read file into int array
how to read text file in java and store it to an arraylist
java read file into array
java read text file into 2d array of integers
reading a file into an arraylist of objects java

So we have this program where we have to read double values from a text file into a double ArrayList and make certain calculations.

example of the text file:

Note: there's space between the date and the double values

5/05/1998 4.4

1/01/1999 -4.123

the problem is that i'm getting is as below:

"NumberFormatException for input string: 1/2/1950 0.0258" error.

Here's my code:

public static void value() throws java.io.IOException{
    try{
        BufferedReader br = new BufferedReader(new FileReader(new File("SP500-Weekly.txt")));
        ArrayList<Double>list = new ArrayList<Double>();
        String line;
        while((line=br.readLine())!=null){
            String[] r = line.split("    ");
            for(int i=0; i<r.length; i++){
                double val = Double.parseDouble(r[i]);
                list.add(val);
            }
        }br.close();
        System.out.println(list.size());
    }
    catch(IOException io){
        System.out.println("error");
    }
}

Seems like you just need the double value present on each line and want to add it into a List<Double>. Based off of your input, second value is always your double value, but you are trying to parse first value as well which is a date and Double.parseDouble() cannot parse characters that comes in a date such as /, thus you ran into exception. If the double value is what you need then do it simply as :

try {
        BufferedReader br = new BufferedReader( new FileReader( new File( "SP500-Weekly.txt"" ) ) );
        List<Double> list = new ArrayList<Double>();
        String line;

        while ( ( line = br.readLine( ) ) != null ) {

            String[] r = line.split( "\\s+" );
            list.add( Double.parseDouble( r[ 1 ] ) );
        }
        br.close( );
        System.out.println( list.size( ) );
    } catch ( IOException io ) {
        e.printStackTrace( );
    }

You can then play around with list variable as your wish.

Also if you want to be more specific and check if it's actually number/double for second value then I'd do following to add a regex which will make sure that the second value is number (with or without - sign) as below:

while ( ( line = br.readLine( ) ) != null ) {
            String[] r = line.split( "\\s+" );
            for ( String string: r ) {
                if ( string.matches( "^-?[0-9]?.?[0-9]+" ) ) {
                    list.add( Double.parseDouble( r[ 1 ] ) );
                }
            }
        }

java - How to read doubles from .txt file into an ArrayList, When you create Scanner like this new Scanner(new File("input100K.txt").​getAbsolutePath()) ; you are scanning file path as input not file itself. Do it this way new  In this tutorial, we'll discuss different ways of reading a file into an ArrayList. There are many ways to read a file in Java. Once we read a file, we can perform a lot of operations on the content of that file. Some of these operations, like sorting, may require processing the entire content of the file into memory.

A very simple and up to date implementation of this using java.nio and pure Java 8 would the following.

private static List<Double> readDoubles(final String fileName) {
   try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
            return stream.map(s -> s.split("\\s+")[1])
                .map(Double::parseDouble)
                .collect(Collectors.toList());
   } catch (IOException e) {
       e.printStackTrace();
   }
   return Collections.emptyList();
}

Implementation also takes the liberty of using try-with-resources to auto manager the various resources.

Java: Read a File into an ArrayList, Since Java 7, it's possible to load all lines of a file into an ArrayList in a very We can also specify a charset to handle different formats of text, if necessary: Introduction There are many ways to go about Reading and Writing Files in Java [/reading-and-writing-files-in-java/]. We typically have some data in memory, on which we perform operations, and then persist in a file. However, if we want to change that information, we need to put the contents of the file back into memory and perform operations. If, for an example, our file contains a long list

CORRECTCODE:

import java.util.List;
class Sample extends SimulateMarket{
    public static void value(){
    try{
        BufferedReader br = new BufferedReader(new FileReader(new File("SP500-Weekly.txt")));
        List<Double> list = new ArrayList<Double>();
        String line;
        while((line=br.readLine())!=null){
            String[] r = line.split("\\s+");
            list.add(Double.parseDouble(r[1]));
        }br.close();
        Random rand = new Random();
        int randomIndex = rand.nextInt(list.size());
        System.out.println(list.get(randomIndex));
    }
    catch(IOException io){
        System.out.println("error");
    }
}

}

Read a File into an ArrayList, A quick tutorial to reading files into ArrayLists in Java. such operations, we may need to read the file as an Array or a List of lines or words. Scanner is a simple text scanner, used for parsing primitive types and strings,  Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information. Reading numbers from a text file into an ArrayList in

How to read a text file into ArrayList in Java, How do I add data to an ArrayList in Java? Lets take a look at two examples of the first flavor. Below is an example of a C++ program that reads in a 4 line file called “input.txt” and puts it in an array of 4 length. Remember indexes of arrays start at zero so you have subscripts 0-3 to work with. After that is an example of a Java program which also controls the limit of read in

I am being asked to read data from a .txt file into an array, and do , So you want to parse the file and then maybe put the values in a data I am being asked to read data from a .txt file into an array, and do things with that List<Integer>list = new ArrayList<Integer>(); Then look at Double and Integer for how to turn the strings into numbers that you can do all your math operations on. How do you read the contents of a file into an ArrayList<String> in Java? Here are the file contents: Just read each word into the ArrayList. Use s.hasNextLine () and s.nextLine () if you want to read in line by line instead of word by word. Oh nice, shorter with Scanner than BufferedReader and no exceptions to deal with.

File Input, The following is an example of reading in a very simple plain text file. ArrayList; class ReadFile { public static void main(String[] args) { File f = new public class Book { private String title; private String author; private double price; public  Read text file and load data to an array. Follow 1,340 views (last 30 days) I would like to read this text file and store into an array, for example.

Comments
  • Can you format the value in text file to be exactly what you are trying to load? Are each record present in new line?
  • yes every record is in a new line.
  • And what is your output supposed to be like? It is all doubles values in a single list?
  • Why are you splitting by 4 spaces? Shouldn't you split by single space and read only the second part of the result?
  • @stackFan, the doubles should be stored in a arraylist and then we have to access one of those randomly using Double value = data.get(r.nextInt(data.size()));.
  • Closing your resources manually or yet better using a try with resources would have been very nice. Also coding to the implementation rather than the interface is not correct.
  • @Aris_Kortex thanks for suggestion. Initially I wrote to address the main issue OP was having. Now the code has been updated.
  • This also obviously wrong. You catch and throw the same exception. Either do one of them. Also you're still using the concrete implementation for the initialization of the list.
  • The catch/throw thing i've fixed; however, i'm learning java basics at my college and i'm not familiar with the term "concrete implementation."
  • This is referring to this ArrayList<Double>list = new ArrayList<Double>();. Use this List<Double> list = new ArrayList<Double>(); instead.