0
I made a code that generates a square matrix N x N with random numbers. So far ok. I made a method to record this matrix in a file .txt
, only that the matrix simply comes out with random values, even though I do the conversion of the whole matrix structure int
for String
.
Follow the main class:
import java.util.Scanner;
import java.util.Random;
import java.io.IOException;
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
System.out.print("De o valor para dimensão de uma matriz quadrada: ");
int N = in.nextInt();
int [][] matrix1 = new int[N][N];
//double [][] matriz2 = new double[N][N];
Random rand = new Random();
rand.setSeed(System.currentTimeMillis());
for (int i = 0 ; i < N ; i++) {
for (int j = 0 ; j < N ; j++) {
Integer r = rand.nextInt()% 1000;
matrix1[i][j] = Math.abs(r);
}
}
System.out.println("A matriz quadrada gerada de tamanho " + N + " foi:");
printMatrix graph = new printMatrix();
graph.printGraph(matrix1, N);
graph.matrixToFile(matrix1);
}
So I made a class with two methods:
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
public class printMatrix {
public void printGraph(int[][] array, int n) {
for (int i = 0; i < n; i++) {
System.out.print("[");
for (int j = 0; j < n; j++) {
System.out.print(array[i][j] + " ");
}
System.out.println("]");
}
System.out.print("\n");
}
public void matrixToFile(int[][] array) throws IOException {
FileWriter arqMatrix = new FileWriter("Matriz 1.txt");
PrintWriter gravarArq = new PrintWriter(arqMatrix);
gravarArq.println(Arrays.toString(array));
arqMatrix.close();
System.out.println("Arquivo 'Matriz 1.txt' no mesmo local do projeto.\n");
}
}
So far so good. The problem is when I do this function "gravarArq.println(Arrays.toString(array));
". It gets random characters, like in bytes, like: [[I@28d93b30
, [I@1b6d3586
, [I@4554617c]
(in case of placing 3, it always generates this depending on how the "N".
If you put a System.out.println(Arrays.toString(array));
you generate these random values on the console itself, or place a + "teste"
at the end of gravarArq.println(Arrays.toString(array));
getting gravarArq.println(Arrays.toString(array) + "teste");
There will be a "test" at the end of the file, that’s how I realized that is not recording in bin/bytes. I don’t mean even by skipping the lines, but because these values are coming out like this.
I would also like to know how to skip lines and format exactly as in the console.
Just switch where you used System.out.println for
handler.write()
(assuming you are using Filewriter), since you have assembled a method that solves item by item an array rather than using Arrays.toString– Guilherme Nascimento