Fill a 2d array with text file, comma separated values - java

Hi i want to fill a 2d array with comma separated values like this
3
1,2,3
4,5,6
7,8,0
first number the size of the array, the next values are the values of the array this is my code at the moment
//readfile
public static void leeArchivo()
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try
{
//read first value which is teh size of the array
size = Integer.parseInt(br.readLine());
System.out.println("size grid" + size);
int[][] tablero = new int[size][size];
//fill the array with the values
for (int i = 0; i < tablero.length; i++)
{
for (int j = 0; j < tablero[i].length; j++ )
{
tablero[i][j] = Integer.parseInt(br.readLine());
}
}
br.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
This method is working fine for me, just another question, this will work if I want to insert another 2d array of the same size next to the other?
public static void leeArchivo()
{
Scanner s = new Scanner(System.in);
size = Integer.parseInt(s.nextLine());
tablero = new int[size][size];
boolean exit = false;
while (!exit) {
for (int i = 0; i < size; i++) {
//quit commas to fill array
String valuesStrArr[] = s.nextLine().split(",");
for (int j = 0; j < size; j++) {
tablero[i][j] = Integer.parseInt(valuesStrArr[j]);
}
if (i == size - 1)
exit = true;
}
}
}
Example:
3
1,2,3
4,5,6
7,8,0
1,2,3
8,0,4
7,6,5

Solution using Scanner
Scanner s = new Scanner(System.in);
int size = Integer.parseInt(s.nextLine());
int[][] tablero = new int[size][size];
boolean exit = false;
while (!exit) {
for (int i = 0; i < size; i++) {
String valuesStrArr[] = s.nextLine().split(",");
for (int j = 0; j < size; j++) {
tablero[i][j] = Integer.parseInt(valuesStrArr[j]);
}
if (i == size - 1)
exit = true;
}
}

Scanner in = new Scanner(System.in);
int num = in.nextInt();
Use Scanner. Replace System.in with File.

First, you have to separate the elements.
You can do this using the String method split (https://www.javatpoint.com/java-string-split)
//fill the array with the values
for (int i = 0; i < tablero.length; i++)
{
String[] elements = br.readLine().split(",");
for (int j = 0; j < tablero[i].length; j++ )
{
tablero[i][j] = Integer.parseInt(elements[j]);
}
}
br.close();
Or you can use Scanner method, nextInt.
Regarding perfomance, the first option is better.

Related

How to read int numbers (matrix) from file.txt and add to array?

I want to multiply two matrices. I have 2 files with 2 different integers (matrices).
file1.txt
4 3 4 6
-1 10 4 -1
4 7 2 -8
file2.txt
3 0 0
0 3 0
0 0 3
0 2 4
How can I read these files separately into a two-dimensional array, so that it is convenient to multiply. I've a code where the size of the matrix is indicated at the beginning, but what if there could be different size of matrices? Here is my code with given size:
public static void main(String[] args) throws IOException {
try {
Scanner input = new Scanner(new File(file1.txt));
int m = 3; // I need the size for random matrix
int n = 5; // I need the size for random matrix
int[][] a = new int[m][n];
while (input.hasNextLine()) {
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
try{
a[i][j] = input.nextInt();
System.out.println("number is "+ a[i][j]);
}
catch (java.util.NoSuchElementException e) {
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
It would be better to implement a separate method reading a file into matrix if the dimensions of the matrix are known:
public static int[][] readFileWithMatrix(String filename, int rows, int cols) throws Exception {
int[][] arr = new int[rows][cols];
try (Scanner input = new Scanner(new File(filename))) { // use try-with-resources to close Scanner
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
arr[i][j] = input.nextInt();
}
}
}
return arr;
}
Then it would be simpler to use this method:
int[][] arr3x4 = readFileWithMatrix("file1.txt", 3, 4);
int[][] arr4x3 = readFileWithMatrix("file2.txt", 4, 3);
//... do matrix multiplication
Here try the following code which takes all the input from file assuming that it contains only the matrix elements and store it into a dynamic 2D array a e.g., list of list. First I read the first line of the file and take out all the numbers from it which gives me the total number of columns of the matrix. Next I keep on reading the input lines until the end of file which expands the row of the matrix a
public static void main(String[] args) throws IOException {
try {
Scanner input = new Scanner(new File(file1.txt));
List<ArrayList<Integer>> a = new ArrayList<ArrayList<Integer>>();
int row=0;
String cols[] = input.nextLine().split(" ");
a.add(row, new ArrayList<Integer>());
for (int j = 0; j < cols.length; j++) {
try {
a.get(row).add(Integer.parseInt(cols[j]));
} catch (Exception e) {
}
}
row++;
while (input.hasNextLine()) {
a.add(row, new ArrayList<Integer>());
for (int j = 0; j < cols.length; j++) {
try {
a.get(row).add(input.nextInt());
} catch (java.util.NoSuchElementException e) {
}
}
row++;
}
System.out.println("Rows: "+row+" Columns: "+cols.length);
for (int i = 0; i < a.size(); i++) {
for (int j = 0; j < a.get(i).size(); j++) {
System.out.println("Number is "+ a.get(i).get(j));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
Demo code in here: https://ideone.com/ZEcgPR#stdin

How stop array input limit then the result to show the output?

I have a question about stop array input limit then the result to show the output.
Below is my coding have already set new float[3][3]:
import java.util.Scanner;
public class Clone2Darray {
public static float[][] clone(float[][] a) throws Exception {
float b[][] = new float[a.length][a[0].length];
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
b[i][j] = a[i][j];
}
}
return b;
}
public static void main(String args[]) {
Scanner sc = new Scanner (System.in);
System.out.println ("Type nine float numbers two-dimensional array of similar type and size with line breaks, end by -1:");
float[][] a = new float[3][3];
for (int i=0; i<3; i++){
for (int j=0; j<3; j++){
String line = sc.nextLine();
if ("-1".equals(line)){
break;
}
a[i][j]=Float.parseFloat(line);
}
}
System.out.println("\n The result is:");
try {
float b[][] = clone(a);
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
System.out.print(b[i][j] + " ");
}
System.out.println();
}
} catch (Exception e) {
System.out.println("Error!!!");
}
}
}
The limit output is show me like below:
run:
Type float numbers in the two-dimensional array of similar type and size
with line breaks, end by -1:
5.33
9.33
63.33
6.36
3.55
7.25
2.33
3.66
The result is:
6.33 5.33 9.33
63.33 6.36 3.55
7.25 2.33 3.66
BUILD SUCCESSFUL (total time: 31 seconds)
My problem is want to stop limit float[3][3] and can unlimited key in the input until type -1 to stop the input. May I know how to remove the limit float[3][3] in the array? Hope anyone can guide me to solve my problem. Thanks.
At the point when you allocate memory for the two-dimensional array you have to tell the sizes of its elements, because memory will be allocated for that array and the amount of memory to be allocated must be known.
You can bypass this, by using some more dynamic types, like List and its popuplar implementation, ArrayList, even in a nested form. That's a nice thing to do, but then you will not have a "real" array.
The below code allows you to create the dynamic arrays.
import java.util.Scanner;
public class Clone2DArray {
public static float[][] clone(float[][] a) throws Exception {
float b[][] = new float[a.length][a[0].length];
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
b[i][j] = a[i][j];
}
}
return b;
}
public static void main(String args[]) {
Scanner sc = new Scanner (System.in);
System.out.println("enter row size");
int row = Integer.parseInt(sc.nextLine());
System.out.println("enter column size");
int column = Integer.parseInt( sc.nextLine());
System.out.println ("Type float numbers two-dimensional array of similar type and size with line breaks:");
float[][] a = new float[row][column];
for (int i=0; i<row; i++){
for (int j=0; j<column; j++){
String line = sc.nextLine();
if ("-1".equals(line)){
break;
}
a[i][j]=Float.parseFloat(line);
}
}
System.out.println("\n The result is:");
try {
float b[][] = clone(a);
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
System.out.print(b[i][j] + " ");
}
System.out.println();
}
} catch (Exception e) {
System.out.println("Error!!!");
}
}
}

Reading data from file into 2d array

I need to read a file with a magic square in the format of:
#
# # #
# # #
# # #
where the first line represents the square size and create a 2d array with the file values.
I set up my readMatrix method to read through the lines, created a 2d array of the correct size and input each value to its correct position.
private int[][] readMatrix(String fileName) throws
FileNotFoundException {
int n;
File file = new File(fileName);
Scanner fileScan = new Scanner(file);
String line = fileScan.nextLine();
Scanner lineScan = new Scanner(line);
n = lineScan.nextInt();
square = new int[n][n];
while (fileScan.hasNextLine()) {
line = fileScan.nextLine();
while (lineScan.hasNext()) {
for (int i = 0; i < n; i++) {
lineScan = new Scanner(line);
for (int j = 0; j < n; j++) {
square[i][j] = lineScan.nextInt();
}
}
}
}
fileScan.close();
lineScan.close();
return square;
public int[][] getMatrix() {
int[][] copy;
int n = square.length;
copy = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
copy[i][j] = square[i][j];
}
}
return copy;
However the tester for this program displays a magic square of the correct dimensions but with all the values being 0 and fails the getMatrix method(I'm assuming because the returned square doesn't match the file square). I tried moving the scanner objects around(inside/outside) the for/while loops in the readMatrix and tried using parseInt/scan next instead of nextInt with no success. I am stumped.
Try this code is able to display 1 - 9 from the 3 x 3 matrix. The variable type can be changed to your need. I used 'char' for ease.
private static char[][] finalmatrix;
public static void main(String[] args) throws Exception {
finalmatrix = readMatrix("File.txt");
// Output matrix.
for (int i = 0; i < finalmatrix.length ;i++) {
for (int j = 0; j < finalmatrix[i].length ;j++) {
System.out.print(finalmatrix[i][j] + " ");
}
System.out.println("");
}
}
private static char[][] readMatrix(String fileName) throws IOException {
File file = new File(fileName);
Scanner scan = new Scanner(file);
int countRow = 0;
int countColumn = 0;
List temp = new ArrayList();
while (scan.hasNextLine()) {
String line = scan.nextLine();
for (int i = 0; i < line.length(); i++) {
// Count the number of columns for the first line ONLY.
if (countRow < 1 && line.charAt(i) != ' ') {
countColumn++;
}
// Add to temporary list.
if (line.charAt(i) != ' ') {
temp.add(line.charAt(i));
}
}
// Count rows.
countRow++;
}
char[][] matrix = new char[countRow][countColumn];
// Add the items in temporary list to matrix.
int count = 0;
for (int i = 0; i < matrix.length ;i++) {
for (int j = 0; j < matrix[i].length ;j++) {
matrix[i][j] = (char) temp.get(count);
count++;
}
}
scan.close();
return matrix;
}

How do i get characters in a file into a 2D array in Java?

So i have a file that looks like this:
+-+-+-+ ("/n")
|S| | ("/n")
+ + + + ("/n")
| |E| ("/n")
+-+-+-+ ("/n")
/n being a new line in the file
and i want to have each character here as an entry in a 5x7 array. I do not know how to do it, this is what i have tried (along with a lot of other things. input is the file):
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new File("maze0.txt"));
char maze[][] = new char[5][7];
int charCount = 0;
for (int row = 0; row < finalHeight; row++) {
for (int col = 0; col < finalWidth; col++) {
while (input.hasNextLine()){
String line = input.nextLine();
if ((row < finalHeight - 1 || col < finalWidth) && charCount < line.length()) {
maze[row][col] = line.charAt(charCount);
charCount += 1;
System.out.print(maze[row][col]);
But this prints out +S+ + which is not right. I am a brand new beginner programmer and having a hard time with this, thanks for any help you can offer.
I fixed it!! this is what I did:
Scanner input = new Scanner(new File("maze0.txt"));
char maze[][] = new char[5][7];
input.nextLine();
for (int row = 0; row < 5; row++) {
String fileLine = input.nextLine();
for (int col = 0; col < 7; col++) {
char nextChar = fileLine.charAt(col);
maze[row][col] = nextChar;
System.out.print(maze[row][col]);
Actually, while the screen might display +S+ +, you only have one value in your array - at maze[0][0] (a value of '+'). Your while loop reads the entire file before the for loops ever increment.For each line it reads, it sets maze[row][column] = line.charAt(charCount); -- but row and column never get incremented because, well, there's another line to read. So it reads another line and overwrites maze[0][0] to be the line.charAt(1) (because you incremented charCount). This character is the space. Then it loops back through because there's another line to read, and puts the 3rd character at maze[0][0]. So on and so forth. When it's read the entire file, then it steps through the for loops, but while (input.hasNextLine()) doesn't execute because it's already read the entire file.
Here is a simple and efficient way to do it.
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new File("maze0.txt"));
char maze[][] = new char[5][7];
for (int i = 0; i < maze.length; i++) {
//Get each line and convert to character array.
maze[i] = input.nextLine().toCharArray();
}
}
You can read each line from the file and convert it to char array.
public static void main(String[] args) throws IOException {
Scanner scan = new Scanner(new File("maze0.txt"));
String b;
char maze[][] = new char[5][7];
for (int row = 0; row < 5; row++) {
while ( scan.hasNextLine() ){
b = scan.nextLine();
maze[row] = b.toCharArray();
System.out.println(maze[row]);
}
}
scan.close();
}
you just need two loops why are you running 3 loops?
Scanner sc = new Scanner(new File("maze.txt"));
String line = null;
for(int i = 0; i< 5;i++)
{
line = sc.readLine()
for(int j = 0; j < 7; j++)
{
maze[i][j] = line.charAt(j);
}
}
This snippet should read the file and store it in a matrix.
Since you are reading the line in the inner loop, you are printing the diagonal.
Convert the line to character array using .toCharArray() That will give you an array of all the characters. Then just feed them into your array.
it'd look something like..
// everytime we come to a new row, read a line from the file, convert it into letters then proceed on feeding them into columns.
for (int row = 0; row < finalHeight; row++)
{
String line = input.nextLine();
Char[] chars = line.toCharArray();
if(!input.hasNextLine())
break; // if there is no more lines to read, break the loop.
for (int col = 0, i = 0; (col < finalWidth && i < chars.length); col++,i++)
{
maze[row][col] = chars[i];
System.out.print(maze[row][col]);
}
}
import java.io.*;
import java.util.*;
public class B
{
public static void main(String...aaadf)throws FileNotFoundException
{
Scanner sc = new Scanner(new File("D://maze.txt"));
char maze[][] = new char[5][7];
String line = null;
for(int i = 0; i< 5;i++)
{
line = sc.nextLine();
for(int j = 0; j < 7; j++)
{
maze[i][j] = line.charAt(j);
}
}
for(int i = 0; i< 5;i++)
{
for(int j = 0; j < 7; j++)
{
System.out.print(maze[i][j]);
}
System.out.println();
}
}
}

how to get int[][] dimensionArray?

I want to get matrix[i][j] to my int[][] gettwodimensionalArray, I try so many way, but when I do the test, my gettwodimensionaArray still not store from matrix[i][j]. Please help me out, thank you.
Here is my code look like.
public int[][] gettwodimensionalArray(String file_name) {
File file = new File(file_name);
ArrayList<int[]> rows = new ArrayList<int[]>();
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] s = line.split("\\s+");
int[] row = new int[s.length];
for (int i = 0; i < s.length; i++) {
row[i] = Integer.parseInt(s[i]);
}
rows.add(row);
System.out.println(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
int numbOfRow = rows.size();
// find number of columns by gettting the lenght of one of the rows row
int keepTrackSizeFirstRow;
for (int i = 0; i < numbOfRow; i++) {
if (i == 0) {
keepTrackSizeFirstRow = rows.get(0).length;
}
// compare current row i's array length, to keetracksizefirstrow
}
int[][] matrix = new int[numbOfRow][rows.get(0).length];
// System.out.println(matrix);
for (int i = 0; i < numbOfRow; i++) {
// i = row
for (int j = 0; j < rows.get(i).length; j++) {
// j = col
matrix[i][j] = rows.get(i)[j];
System.out.print(matrix[i][j]);
}
}
return matrix;
}
Not sure what you are trying to do. If you want each row of the input to fit in the array, you can declare the array with variable sizes, like this:
int[][] matrix = new int[numbOfRow][];
for (int i = 0; i < matrix.length; i++) {
matrix[i] = new int[rows.get(i).length];
}
If instead you want all rows to have the same length, you should find the maximum length of the input like this:
int maxlength = 0;
for (int i = 0; i < rows.size(); i++) {
maxlength = (rows.get(i).length > maxlength) ? rows.get(i).length : maxlength;
}
int[][] matrix = new int[numbOfRow][maxlength];

Categories

Resources