-1

I have a .txt file with 300 rows and 785 columns with a bunch of numbers in E notation (e.g. -6.431571950262252035e-02). How would I covert those numbers into a 2-D array?

This is all I have:

 double[][] hiddenArray = new double[300][785];  

 Scanner scanner = new Scanner(System.in) ;
 String hiddenFile = "hidden-weights.txt";
 String outputFile = "output-weights.txt";
 scanner.close();

 Scanner in = new Scanner(new File(hiddenFile));
 String hidden= in.nextLine();
vefthym
  • 7,422
  • 6
  • 32
  • 58

1 Answers1

0

Use Scanner::hasNext() to loop while there are more lines and Scanner::nextLine() to fetch the next line, then use String::split() to get an array of strings on each line (Note: my presumption is that the columns are separated by commas (i.e. ,) but feel free to adjust for your needs). For parsing the numbers in e notation, use Double.valueof(), and add that value to the array (e.g. hiddenArray).

You should be able to use the sample below. I also created an example on tutorialspoint.com codingGround but that may not work...

    try {
        String delimiter = ","; //separates columns - change for your needs

        int row = 0;
        Scanner in = new Scanner(new File(hiddenFile));
        String line;
        while (in.hasNext() && (line = in.nextLine()) != null )   {
            String[] vals = line.trim().split(",");

            for (int col = 0; col < vals.length; col++) {
                hiddenArray[row][col] = Double.valueOf(vals[col]);
            }
            row++;
        }    
    }
    catch(FileNotFoundException e) {
        System.out.println("file not found - "+e.getMessage());
    }
Sᴀᴍ Onᴇᴌᴀ
  • 8,218
  • 8
  • 36
  • 58