简体   繁体   中英

Issue with reading and storing data from .txt file into array

Program:

  1. User enters a file name containing numbers (1 per line)
  2. File is read and data is stored in StringBuffer
  3. StringBuffer is converted to String type
  4. String is split() and stored in a String[]
  5. Double[] is created and converts/stores elements of the String[]

The above is what I am trying to achieve; however, the program is not working. *Look below for an example...

class tester
{
public static int x = 0;
public static double[] dataArray = new double[x];//array storing elements

public static void main(String[] args) throws IOException
{
    //userInput .txt
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter filename:\n");
    String name = sc.nextLine();

    File file = new File(name);
    FileReader fileReader = new FileReader(file);
    BufferedReader bufferedReader = new BufferedReader(fileReader);
    StringBuffer stringBuffer = new StringBuffer();
    String newString = stringBuffer.toString();

    String [] stringArray = newString.split("\n");
    double [] dataArray = new double[stringArray.length];

    for(int i=0 ; i < stringArray.length ; i++)
    {  
        dataArray[i] = Double.parseDouble(stringArray[i]);  
    }

I have a file named: Ben.txt that looks like this:

1
2
3
4
5
6
7
8
9
10

When I run the program...

Enter filename:

c:/Ben.txt
Exception in thread "main" java.lang.NumberFormatException: empty String
at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
at sun.misc.FloatingDecimal.parseDouble(Unknown Source)
at java.lang.Double.parseDouble(Unknown Source)
at tester.main(tester.java:27)

The problem is you are not actually reading anything from the file. You do all the setup but you aren't reading.

So when you have:

    File file = new File(name);
    FileReader fileReader = new FileReader(file);
    BufferedReader bufferedReader = new BufferedReader(fileReader);
    StringBuffer stringBuffer = new StringBuffer();
    String newString = stringBuffer.toString();

Here I don't think you actually need a StringBuffer, all you have to add/replace is this

    String str;
    str = bufferedReader.readLine();

If you want to read the whole file all you have to do is iterate over the entire file using readLine().

As GiantTree said, you are not actually reading in the file at all

Changing the definition of newString to the following will give you some progress.

  String newString = bufferedReader.readLine();

Other things you should consider:

  • closing the resources you've opened
  • exception handling
  • following standard class naming conventions
  • no need to initialise dataArray twice

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM