Input of a 2D array via button and .txt file Processing Java - java

After a thorough survey of this and many other Internet communities I failed to solve my problem. It is about ControlP5 button and my aim of importing 2D array from previously formated text file with two columns and 19 rows and space separated values. Now my code works but the 2D arrray I designated to hold the values from the txt does not get all of the values but just the last pair in its first row. I know that for loops over all values but stores them only in the first row. I dont know how to push it in another row for reading. This is my code:
if(theEvent.isController())
{
if(theEvent.controller().name() == "mean shape males")
{
String loadPath1 = selectInput();
reader = createReader(loadPath1); //new BufferedReader
int x=0; //rows
int y=0; //columns
String smaLine;
try
{
while ((smaLine = reader.readLine()) != null)
{
String[] values = smaLine.split(", ");
for(int i = 0; i < values.length; i++)
{
float[] testC = float(split(values[i], " "));
for (int j = 0; j < testC.length; j++)
{
mat1[j][i] = testC[j]; //THIS IS THE PROBLEMATIC MATRIX
}
}
x = x+1;
}
}
catch (IOException e)
{
e.printStackTrace();
}
mat1max = maxRet(mat1);
mat1min = minRet(mat1);
inputMat = new Grid(2,19,10,130,22,mat1,mat1min,mat1max);
}
}
I used all the advice I could find on Stack Overflow mainly from this post How to print 2D Array from .txt file in Java but I just can`t seem to move the reader onto rows other then the first.

I'm guessing that instead of resetting the elements in mat1 you want to create a new matrix for each line and store them in a list of some kind. This is how you might do it:
List<?> matrices = new ArrayList<?>();
while ((smaLine = reader.readLine()) != null)
{
float[][] mat = new float[MATRIX_ROWS][MATRIX_COLUMNS];
String[] values = smaLine.split(", ");
for(int i = 0; i < values.length; i++)
{
float[] testC = float(split(values[i], " "));
for (int j = 0; j < testC.length; j++)
{
mat[j][i] = testC[j];
}
}
matrices.add(mat);
x = x+1;
}
Where is x used, by the way?

Swap your mat1[j][i] = testC[j] to mat1[i][j] = testC[j]

Related

Get matrix from a file Java

I currently have a text file in the format
matrix
row
a
b
c
row
d
e
f
row
g
h
i
row
j
k
l
matrix
row
m
n
o
p
q
row
r
s
t
u
v
I would like to convert this into two integer matrices (stored as 2 2D arrays), in the format
a b c
d e f
g h i
j k l
and
m n o p q
r s t u v
So far, I have created a Scanner object of the file and put each line in a text array:
Scanner sf = new Scanner(new File("C:\\textfiles\\matrices.txt"));
int maxIndex = -1;
String text[] = new String[10000]; // I added more than necessary for safety
while (sf.hasNext()){
maxIndex++;
text[maxIndex] = sf.nextLine();
}
sf.close();
This way, the text file is now contained in a string array, where each line is a new element of the array. Right now, I would like to partition the array into two arrays with each array being the matrices. How should I continue? (note: I am a total beginner and desire answers that are simple (no arraylist, hashmap, etc., and that's why this question is not a duplicate of How to read two matrices from a txt file in java because it uses BufferedReader, and there are other potential duplicate questions, so I would like to clear this up)
What I currently have after the top:
int counter = 0;
int iCounter = 0; // row
int jCounter = 0; // column
int matrix1[][];
int matrix2[][];
while (counter < maxIndex){
if (counter = 0)
{
\\not yet written...
}
\\not yet written...
}
As #Rob said, it's really cumbersome to do this without dynamic data structures such as ArrayList's. But nevertheless, here's a code that does your job (considering you have only two matrices), without using any List's:
int counter = 0;
int iCounter = 0; // row
int jCounter = 0; // column
int matrix1[][];
int matrix2[][];
int rowSize = 0, numberOfRows = 0;
counter = 2;
while (!text[counter].equals("row") && !text[counter].equals("matrix")) {
counter++;
rowSize++;
}
//now we have the row size
numberOfRows = 1;
while (!text[counter].equals("matrix")) {
if (text[counter].equals("row"))
numberOfRows++;
counter++;
}
//now we have the total number of rows
matrix1 = new int[numberOfRows][rowSize];
counter = 2; //to start from the first matrix
//now counter should point to the first row of the first matrix
while (!text[counter].equals("matrix")) {
jCounter = 0;
while (!text[counter].equals("row")
&& !text[counter].equals("matrix")) {
matrix1[iCounter][jCounter++] = Integer.parseInt(text[counter]);
//supposing your input is Integers, otherwise, you can change
//it to the corresponding type (i.e. Long, Double, etc)
counter++;
}
iCounter++;
if (!text[counter].equals("matrix"))
counter++;
}
//now we finished with the first matrix, and the counter points to
//the first "row" of the second matrix, so we do the same thing again
rowSize = 0;
numberOfRows = 0;
int startOfSecondMatrix = counter + 2; //save this for later
counter += 2; // so that counter points to the first number
while (counter < text.length && !text[counter].equals("row")) {
counter++;
rowSize++;
}
numberOfRows = 1;
while (counter < text.length) {
if (text[counter].equals("row"))
numberOfRows++;
counter++;
}
matrix2 = new int[numberOfRows][rowSize];
counter = startOfSecondMatrix;
iCounter = 0;
while (counter < text.length) {
jCounter = 0;
while (counter < text.length && !text[counter].equals("row")) {
matrix2[iCounter][jCounter++] = Integer.parseInt(text[counter]);
counter++;
}
iCounter++;
counter++;
}
For each matrix we perform the same operations:
-We first go through the matrix to count its size to be able to initialize it, after that, we go row by row, and parse each number.
You might as well put all the work for one matrix into a function (and take care of the bounds) and call it as long you still have more matrices.
This does what you want. Unfortunately doing this with 2D arrays is considerably harder since once you set the size of an array its difficult to manage changing it. Therefore using ArrayList is much easier.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class Main {
public static final String MATRIX = "matrix";
public static final String ROW = "row";
public static void main(String[] args) throws FileNotFoundException {
// Use correct file name here
Scanner sf = new Scanner(new File("matrices.txt"));
// This is a List of 2D Lists
List<List<List<String>>> matrices = new ArrayList<>();
// easier to process lines as we're reading them in so we
// only iterate over the file once
while (sf.hasNext()) {
boolean hasBeenProcessed = false;
String inputValue = sf.nextLine();
switch (inputValue) {
case MATRIX:
ArrayList<List<String>> matrix = new ArrayList<>();
matrices.add(matrix);
hasBeenProcessed = true;
break;
case ROW:
List<List<String>> currentMatrix = getMatrixBeingProcessed(matrices);
currentMatrix.add(new ArrayList<String>());
hasBeenProcessed = true;
break;
}
if (!hasBeenProcessed) {
List<List<String>> currentMatrix = getMatrixBeingProcessed(matrices);
List<String> currentRow = getCurrentRow(currentMatrix);
currentRow.add(inputValue);
}
}
// Print out the results:
int i = 1;
for (List<List<String>> matrix : matrices) {
System.out.println("Matrix " + i);
for (List<String> row : matrix) {
for (String element : row) {
System.out.print(element + " "); // no newline until end of the row
}
System.out.println(); // new line
}
i++;
System.out.println(); // new line
}
}
private static List<String> getCurrentRow(List<List<String>> currentMatrix) {
int lastRow = currentMatrix.size() - 1;
return currentMatrix.get(lastRow);
}
private static List<List<String>> getMatrixBeingProcessed(List<List<List<String>>> matrices) {
int lastMatrix = matrices.size() - 1;
List<List<String>> currentMatrix = matrices.get(lastMatrix);
return currentMatrix;
}
}
Output:
Matrix 1
a b c
d e f
g h i
j k l
Matrix 2
m n o p q
r s t u v
Process finished with exit code 0
Since you don't want to use List and arrays can't be resized once initialized, this is not easy.
There are two ways: Read the file and initialize arrays knowing the size (as #Maaddy posted) or 'resizing' arrays. That's not possible but it is if you use Arrays.copyOf() so you can create a new array.
The idea is create a 'tridimensional' array where you can store: matrix, row and column; and then start to read the file.
Every time you find a word the entire array will be updated creating a new array with one length more.
If the word is 'matrix' the extra length will be added to the first position (the position who 'store' the matrix)
If the word is 'row' then the space will be added for the current matrix. So in this way, the current matrix will have one more array where store the column values.
If the word is other then is a value for the column. The column is resized and added to the correct position.
Note that if a word 'matrix' or 'row' is found, the new array is initialized with no length. This is because will be resized later, when is necessary.
The code is as follows:
//Initialize array with no positions
String[][][] arrays = new String[0][0][0];
Scanner sf = new Scanner(new File("path/matrices.txt"));
int matrix = -1;
int row = -1;
int column = -1;
while (sf.hasNext()){
String line = sf.nextLine();
if(line.equals("matrix")) {
//'Resize' array: Create new array with 1 more length and old data
arrays = Arrays.copyOf(arrays, arrays.length + 1);
//Start new matrix
arrays[++matrix] = new String[0][0];
row = -1;
column = -1;
}else if(line.equals("row")) {
//'Resize' matrix: Create a new array with 1 more length and old data
arrays[matrix] = Arrays.copyOf(arrays[matrix], arrays[matrix].length+1);
row++;
arrays[matrix][row] = new String[0];
column = -1;
}else{
//'Resize' matrix
column++;
arrays[matrix][row] = Arrays.copyOf(arrays[matrix][row], arrays[matrix][row].length+1);
arrays[matrix][row][column] = line;
}
}
sf.close();
//Print result
for(int i = 0 ; i < arrays.length; i++) {
System.out.println("Matrix "+i);
for(int j = 0; j < arrays[i].length; j++ ) {
for(int k = 0; k < arrays[i][j].length; k++) {
System.out.print(arrays[i][j][k]+ " ");
}
System.out.println();
}
System.out.println();
}
And the result is:
Matrix 0
a b c
d e f
g h i
j k l
Matrix 1
m n o p q
r s t u v

Turning 1d array into 2d

I am working on an assignment for my java class and part of the assignment requires reading in a .csv file that is 20x20 and inserting each string into an array.
I am trying to convert my 1d array from the initial reading in of the file into a 2d array, but I seem to be doing something wrong in my output of the data.
I made an add method, and when running the program and calling the method I only get one column of strings and listed in reverse order, but if I do a System.out.println() I don't the output I desire. I am still fairly new to this so I'm sure I just don't see the simple error, but to me, it looks correct.
the reading in of the file
try {
Scanner fileScanner = new Scanner(toOpen);
while (fileScanner.hasNext()) {
fromFile = fileScanner.nextLine();
String temp[] = fromFile.split(" ");
theList.add(temp[0]);
System.out.println(fromFile);
String[][] arr = new String[20][20];
int count = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
arr[i][j] = temp[i];
System.out.print(arr);
}
}
System.out.println();
}
fileScanner.close();
my add method
public void add(String tableValue) { // Adds a new node
Node newNode = new Node(tableValue);
if (isEmpty()) {
setRoot(newNode);
} else {
newNode.setNext(getRoot());
setRoot(newNode);
}
}
and my method that prints the result
public String makeString() { // A Class that makes a string
String theString = new String();
if (isEmpty()) {
theString = "List is empty";
} else {
Node printer = getRoot();
while (printer != null) {
theString += printer.getTableValue() + " ";
printer = printer.getNext();
}
}
return theString;
}
I guess your problem is here:
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
arr[i][j] = temp[i];
This assigns the same value (temp[i]) to all slots in arr[i]. Again guessing, I think you need something like:
int tmpIndex = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
arr[i][j] = temp[tmpIndex];
tmpIndex++;
In other words: you have 400 different values in temp. But your code is only assigning the first 20 values 20 times again and again.
Beyond that: System.out.print(arr); isn't doing what you expect it to do - to learn how to print arrays correctly, see this.
As we don't know the number of lines in a file, we can start by storing each line into an ArrayList (of String[]) and then convert it into a 2D array, e.g.:
List<String[]> lines = new ArrayList<>();
while (fileScanner.hasNext()) {
String line = fileScanner.nextLine();
String temp[] = line.split(" ");
lines.add(temp);
}
Now, convert it into an array:
String[][] array = new String[lines.size()][];
for(int i=0 ; i<lines.size() ; i++){
array[i] = lines.get(i);
}
I hevent seen where you have really used your add and makeString methods, and what is the role of the theList variable.
Also, could you please send your file Content.
any way:
If this is your calling to the add method: theList.add(temp[0]); that means that you are inside an Extended class structure that you have not shown it. but Any way you have not used it to fill the 2d Array in the for loop
the Code here is also error: you insert the same element temp[i] in every line !!!!
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
arr[i][j] = temp[i];
System.out.print(arr);
}
}
You can use a dynamic structure like ArrayList to fill the Elements...

Generating 2D double array from text file

I have a text file
0.4658 0 3
0.4095 0 3
0.4594 0 3
0.4297 0 3
0.3963 0 3
0.4232 0 3
0.4633 0 3
0.5384 0 3
0.5042 0 3
0.4328 0 3
that I want to read into a 2D double array that looks like this.
{{0.4658, 0, 3},
{0.4095, 0, 3},
... (and so on)
{0.4328, 0, 3}}
I have the following code:
public static void main(String[] args) throws Exception{
double[][] ref = null;
ref = matrix("data80.in",10,3);
}
public static double[][] matrix(String filename, int size1, int size2) throws Exception {
double[][] matrix = null;
BufferedReader buffer = new BufferedReader(new FileReader(filename));
String line;
int row = 0;
while ((line = buffer.readLine()) != null) {
String[] vals = line.trim().split("\\s+");
if (matrix == null) {
matrix = new double[size1][size2];
}
for (int col = 0; col < size1; col++) {
matrix[row][col] = Double.parseDouble(vals[col]);
}
row++;
}
buffer.close();
return matrix;
}
But it keeps giving me an outOfBounds exception, and I don't know where I am going wrong. Please help. If anyone has more efficient solutions as well to my problem it would be helpful
It's because of the following for loop:
for (int col = 0; col < size1; col++) {
matrix[row][col] = Double.parseDouble(vals[col]);
}
We are using size1 whereas we should be using size2, following would work:
for (int col = 0; col < size2; col++) {
matrix[row][col] = Double.parseDouble(vals[col]);
}
Also, there is no need for null check inside the for loop, you can remove it and initialise the array in the beginning, e.g.:
public static double[][] matrix(String filename, int size1, int size2) throws Exception {
double[][] matrix = new double[size1][size2];;
BufferedReader buffer = new BufferedReader(new FileReader(filename));
String line;
int row = 0;
while ((line = buffer.readLine()) != null) {
String[] vals = line.trim().split("\\s+");
for (int col = 0; col < size2; col++) {
matrix[row][col] = Double.parseDouble(vals[col]);
}
row++;
}
buffer.close();
return matrix;
}
You have defined you 2d matrix as
matrix = new double[size1][size2];
meaning there are size1 rows and size2 columns but in following line:
for (int col = 0; col < size1; col++) {
you have used size1. So correction is:
for (int col = 0; col < size2; col++) {
Here is yet another concept as to how you can place the delimited numerical data contained within a text file of any number of rows and any number of columns into a Double data type Two Dimensional Array. All you need to do is pass the path and file name to the method. You can also optionally supply the delimiter used within the file, the method default is a comma (,) delimiter since it is one of the most commonly used. Here is the method:
public static double[][] matrix(String filename, String... delimiterInFile) {
String delimiter = ","; // Default data delimiter in file.
// See if a optional data delimiter is supplied...
if (delimiterInFile.length > 0) { delimiter = delimiterInFile[0]; }
// Catch IO Exceptions
try {
//Place the contents of file into a ArrayList
List<String> list = Files.lines(Paths.get(filename)).collect(Collectors.toList());
// Get the greatest number of delimited columns contiained
// within the ArrayList the whole while ignoring blank lines
// (there could be blank lines in file). Our columns for our
// double 2D Array will be determined from this value. We also
// determine the true number of rows required (remember, no
// blank elements allowed so ArrayList.size() wont be good enough).
int r = 0, c = 0;
for (int i = 0; i < list.size(); i++) {
if (!list.get(i).equals("")) {
int l = list.get(i).split(delimiter).length;
if (l > c) { c = l; }
r++;
}
}
// If we have nothing then the get outta here
// by returning null.
if (r == 0 || c == 0) { return null; }
// Declare and initialize a double data type 2D Array
double[][] array = new double[r][c];
// Fill the double type array...
for (int i = 0; i < list.size(); i++) {
if (!list.get(i).equals("")) {
String[] data = list.get(i).split(delimiter);
for (int j = 0; j < data.length; j++) {
array[i][j] = Double.parseDouble(data[j]);
}
}
}
return array;
} catch (IOException ex) {
// Do what you want with the Exception...
ex.printStackTrace();
return null;
}
}
This method will automatically determine the required number of Rows and Columns for the returned Double data type 2D Array. The method ignores blank file lines so the required Rows needed for the returned Double 2D Array is determined with this in mind. The number of Columns value is determined by iterating through the data lines and detecting which data line contains the most delimited data. That column count is used for the entire 2D Array. This means then that file data lines which contain less columns will have their remaining Array Elements filled with a 0.0 double type value.
The optional delimiter that can be passed to this method can be any string or a RegEx (Regular Expression) string, for example: " " or "\\s+" or "," or ", " or "\t", etc.
This method will also throw an IO Exception should there be a problem accessing the supplied data file.
With the data file schema you provided:
0.4658 0 3
0.4095 0 3
0.4594 0 3
0.4297 0 3
0.3963 0 3
0.4232 0 3
0.4633 0 3
0.5384 0 3
0.5042 0 3
0.4328 0 3
and let's assume this file is named data.txt which is in your classpath, you might use this method like this:
double[][] myData = matrix("data.txt", "\\s+");
for (int i = 0; i < myData.length; i++) {
String strg = "";
for (int j = 0; j < myData[0].length; j++) {
strg+= myData[i][j] + " ";
}
System.out.println(strg);
}
Keep in mind, this is not a method I would recommend for really large data files (Hundreds of thousands of lines).

Transpose ArrayList<ArrayList<String>> in Java

I have a method attempting to transpose a ArrayList containing an ArrayList of string, called matrix and return the new array.
I found Transposing Values in Java 2D ArrayList, but it looks like it's for Arrays and not ArrayLists. My 2D array is of unknown dimensions, either rectangular or possibly irregular (but never square).
My idea was to read each inner array, and append the items to the inner arrays of the outgoing matrix.
public static ArrayList<ArrayList<String>> transpose (ArrayList<ArrayList<String>> matrixIn){
ArrayList<ArrayList<String>> matrixOut = new ArrayList<>();
//for each row in matrix
for (int r = 0; r < matrixIn.size(); r++){
ArrayList<String> innerIn = matrixIn.get(r);
//for each item in that row
for (int c = 0; c < innerIn.size(); c++){
//add it to the outgoing matrix
//get matrixOut current value
ArrayList<String> matrixOutRow = matrixOut.get(c);
//add new one
matrixOutRow.add(innerIn.get(c));
//reset to matrixOut
matrixOut.set(c,matrixOutRow);
}
}
return matrixOut;
}
I'm getting an "IndexOutOfBoundsException: Index: 0, Size: 0" error at
//get matrixOut[v]
ArrayList<String> matrixOutRow = matrixOut.get(v);
What am I doing wrong with this thing?
Assumption: Each inner list has same no of elements. This could help you.
public static List<List<String>> transpose(ArrayList<ArrayList<String>> matrixIn) {
List<List<String>> matrixOut = new ArrayList<List<String>>();
if (!matrixIn.isEmpty()) {
int noOfElementsInList = matrixIn.get(0).size();
for (int i = 0; i < noOfElementsInList; i++) {
List<String> col = new ArrayList<String>();
for (List<String> row : matrixIn) {
col.add(row.get(i));
}
matrixOut.add(col);
}
}
return matrixOut;
}
Answering my own question here. This is what I'm now doing:
public static ArrayList<ArrayList<String>> transpose (ArrayList<ArrayList<String>> matrixIn){
ArrayList<ArrayList<String>> matrixOut = new ArrayList<>();
int rowCount = matrixIn.size();
int colCount = 0;
//find max width
for(int i = 0; i < rowCount; i++){
ArrayList<String> row = matrixIn.get(i);
int rowSize = row.size();
if(rowSize > colCount){
colCount = rowSize;
}
}
//for each row in matrix
for (int r = 0; r < rowCount; r++){
ArrayList<String> innerIn = matrixIn.get(r);
//for each item in that row
for (int c = 0; c < colCount; c++){
//add it to the outgoing matrix
//get matrixOut[c], or create it
ArrayList<String> matrixOutRow = new ArrayList<>();
if (r != 0) {
try{
matrixOutRow = matrixOut.get(c);
}catch(java.lang.IndexOutOfBoundsException e){
System.out.println("Transposition error!\n"
+ "could not get matrixOut at index "
+ c + " - out of bounds" +e);
matrixOutRow.add("");
}
}
//add innerIn[c]
try{
matrixOutRow.add(innerIn.get(c));
}catch (java.lang.IndexOutOfBoundsException e){
matrixOutRow.add("");
}
//reset to matrixOut[c]
try {
matrixOut.set(c,matrixOutRow);
}catch(java.lang.IndexOutOfBoundsException e){
matrixOut.add(matrixOutRow);
}
}
}
return matrixOut;
}
I can't assume smooth arrays and I want to still return a nested ArrayList. So now I'm just finding the maximum dimensions and catching all of the out of bounds errors by adding "".
I'm sure there's a cleaner way, but this seems to be working.

Convert a 2d array to a organizing table look

I have convert a txt file into a 2d array, how can I make it look more organize?
My input file look like this:
[Name], Exam1, Exam2, Exam3
John, 99, 88, 89
May, 99, 100, 100
Mary, 100, 100, 100
Peter, 60, 60, 60
Currently I get:
[Name] Exam1 Exam2 Exam3
John 99 88 89
May 99 100 100
Mary 100 100 100
Peter 60 60 60
I want the data looks more like a table which is easier to read, how can I do that?
Code:
public static void main(String[] args) throws Exception{
File file = new File("test.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
int width = 0, height = 0;
String line = "";
/*Find number of row and column of the file.*/
while ((line = br.readLine()) != null)
{
if (width == 0)
{
/*Find the number of row using split method(",")*/
String[] str = line.split(",");
width = str.length;
}
height++;
}
System.out.println("Row : " + height);
System.out.println("Column : " + width);
/*Adding values to the 2D Array.*/
String[][] data = new String[height][width];
br = new BufferedReader(new FileReader(file));
for (int i = 0; i < height; i++)
{
if ((line = br.readLine()) != null)
{
for (int j = 0; j < width; j++)
{
String[] str = line.split(",");
data[i][j] = str[j];
System.out.print( data[i][j] + " ");
}
}
System.out.println("");
}
}
Thank you very much.
try output using printf
or you can use Formatter
I imagine your not going to want all that System.out stuff in your product but I am going to use it in an example, building on yours to show you the basic steps you will need to do.
Basically you need to make two passes over your data. First pass you should calculate the widest row of the data, so you can craft your ---- line. Then you add the like to whatever output type you are building (here it is System.out) and then walk the data again and add that to the output. You should add something like a newline or other terminator. If you want to line up the columns, you do the same thing but in the first step also record in another multi dimensional array the widest data in each column, and pad data that is shorter that the widest in each column when outputting (this will alter the width of your --- line so you will need to calculate this before building that line of course).
Here is your example modified a little bit with some of these ideas (not padding to line up the columns though, that is for you to do, it is easy trust me)
public static void main(String[] args) throws Exception {
/* Adding values to the 2D Array. */
String[][] data = { { "John", "99", "88", "89" },
{ "May", "99", "100", "100" } };
int wideRowWidth = 0;
int curRowWidth;
// WALK DATA ONCE TO FIND THE WIDEST ROW
for (int i = 0; i < data.length; i++) {
curRowWidth = 0;
for (int j = 0; j < data[i].length; j++) {
curRowWidth += data[i][j].length();
}
if (curRowWidth > wideRowWidth) {
wideRowWidth = curRowWidth;
}
}
// BUILD YOUR DASHED LINE
for (int i = 0; i < wideRowWidth + data[0].length -1; i++) {
System.out.print("-");
}
System.out.print("\n");
// USE YOUR DATA
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data[i].length; j++) {
System.out.print(data[i][j] + " ");
}
System.out.print("\n");
}
}
You can do it in this way, which is as follows :
// To Store and Show Values on the screen.
int columnWidth = 15;
for (int i = 0; i < height; i++)
{
if ((line = br.readLine()) != null)
{
// After reading, we are seperating them.
String[] str = line.split(", ");
for (int j = 0; j < width; j++)
{
data[i][j] = str[j];
// Here we are making the word length of each String equal,
// i.e. equal to column width. So that each String value comes
// below each other. Increase the value of columnWidth variable
// if you want to increase the width of a column or vice versa.
System.out.format("%-" + columnWidth + "s", data[i][j]);
}
}
System.out.print("\n");
}
Hope that might help.
Regards

Categories