Hi, I have a text file that I'm going to read, and then parse it. After parsing it, how do I return it into it's original position or layout as before? Because now after parsing it, my output is printed out individually, instead of printing it out how it looks like originally. May I know how to do it?

My text file actually contains only numbers (decimal and has negative numbers too). I actually want to store the output after parsing into a 2D array, but it doesn't seem to work. I need some help here.

Dani AI

Generated

Quick diagnosis: the numbers are being printed one-per-line because the code prints each parsed value with println inside the inner loop and never advances/uses row/column indexes correctly — a and b in the posted code are never incremented, so the array isn’t filled as a table. To preserve the original line/column layout you must (a) parse and store a full row, then (b) print the row as a single line (or keep the original line string).

A simple, reliable pattern that avoids fixed-size arrays is to store each row as a double[] and print rows after parsing:

import java.io.*;
import java.util.*;

List<double[]> rows = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader("input.txt"))) {
    String line;
    while ((line = br.readLine()) != null) {
        String[] parts = line.split("\\s*,\\s*");
        double[] row = new double[parts.length];
        int col = 0;
        for (String p : parts) {
            if (p.isEmpty()) continue;            // skip stray commas/empty tokens
            row[col++] = Double.parseDouble(p);
        }
        rows.add(Arrays.copyOf(row, col));      // shrink if some tokens skipped
    }
}
for (double[] row : rows) {
    StringBuilder sb = new StringBuilder();
    for (int j = 0; j < row.length; j++) {
        if (j > 0) sb.append(", ");
        sb.append(row[j]);
    }
    System.out.println(sb.toString());
}

Practical fixes tied to the thread: as ’s code shows, if you keep mydouble[][] use b = 0 at the start of each new line, mydouble[a][b++] = value; inside the token loop, then a++ after the line. Use System.out.print for tokens and System.out.println() after the row so you get the original row layout. As suggested, if exact original spacing/punctuation must be preserved, also store each raw line (a List<String>) and print that when needed.

Extra notes: trim tokens, catch NumberFormatException to report bad tokens, prefer StringBuilder over += inside loops for performance, and consider streaming (not storing) if the file is very large.

You could get a String and add one line at a time to it, instead of individual integers.

String str="",output="";
          try{
            BufferedReader in = new BufferedReader(new FileReader("input.txt"));
            
            while ( (str=in.readLine()) != null){

                output+=str;
            }
            in.close();
          
        }

After this, you could split the output string into individual characters (numbers) with the " " separator and put them into your 2d array.

Source: http://www.coderanch.com/t/386279/java/java/string-split-any-delimiter

Pattern p = Pattern.compile(myDelimiter, Pattern.LITERAL) ;
String[] result = p.split(myString);

Or, for maximum simplicity but loss of time, read twice from your file. One time number by number, into your 2d array, second time line by line into the string.

I don't quite get it. As for the first part, the output is actually empty right? It's not the output after I get from reading the file.

Which first part? did you try it ? the output string contains all the lines in the input.txt file.

Yes I know. But in your example, your variable output is actually empty right?

import java.io.*;

public class Testing3
{

	static double[][] mydouble = new double [1000][1000];
    static int a, b;
    static double d;
	static String[] temp;

	public static void main(String args[]) throws Exception
	{

		try
        {
            BufferedReader in = new BufferedReader(new FileReader("C:\\Users\\Serene\\Documents\\Major Project\\Alignment Algorithms\\Testing2.txt"));	//reading files in specified directory

            String str;
            while ((str = in.readLine()) != null)	//file reading
            {
				
				temp = str.split(",");


                for (String s : temp)
                {

                	d = Double.parseDouble(s);
					mydouble[a][b] = d;
					System.out.println(mydouble[a][b]);

                }

			//System.out.println(str);

            }
            in.close();


        }catch( IOException ioException ) {}

	}

}

This is my codes so far. The output of the codes is all individually printed, and not in the original format as the one in the text file.

Yes I know. But in your example, your variable output is actually empty right?

No, it's not, it contains all the codes in their original format. You need to add this to your code:

import java.io.*;

        ...

            String str, output="";   // add this 
            while ((str = in.readLine()) != null)	//file reading
            {
				output=output+str;     // add this
				temp = str.split(",");


                for (String s : temp)
                {

                	d = Double.parseDouble(s);
					mydouble[a][b] = d;
					System.out.println(mydouble[a][b]);

                }

			//System.out.println(str);

            }
            in.close();

        System.out.print(output);      // ADD this

        }catch( IOException ioException ) {}

	}

}

Oh I can only access the output of it outside the while loop? But when I do what you asked me to add, is the output already parsed? However it is not exactly printed the way the original one is.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.