I am asked to write a program that wil generate a random bindary matrix in java
ID: 3757548 • Letter: I
Question
I am asked to write a program that wil generate a random bindary matrix in java and output that array in a txt file.
i wrote the program to generate the random binary array but I cant figure out how to save the outputted matrix to a txt file, any help would be appreciated.
I pasted the program to generate the matrix below
import java.util.Random;
import java.util.Scanner;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
public class anothertest {
public static void main(String args[]) throws FileNotFoundException, UnsupportedEncodingException {
Random random = new Random();
int row, col, i, j;
int arr[][] = new int[1000][1000];
Scanner scan = new Scanner(System.in);
System.out.print("Enter # of array rows ");
row = scan.nextInt();
System.out.print("Enter # of array columns ");
col = scan.nextInt();
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
arr[i][j] = random.nextInt(2);
}
}
System.out.print("The Array is : ");
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}
Explanation / Answer
import java.util.Random;
import java.util.Scanner;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
public class anothertest {
public static void main(String args[]) throws FileNotFoundException, UnsupportedEncodingException {
Random random = new Random();
int row, col, i, j;
int arr[][] = new int[1000][1000];
Scanner scan = new Scanner(System.in);
System.out.print("Enter # of array rows ");
row = scan.nextInt();
System.out.print("Enter # of array columns ");
col = scan.nextInt();
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
arr[i][j] = random.nextInt(2);
}
}
System.out.print("Written in file! ");
try{
FileWriter fw=new FileWriter("C:\filename.txt");
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
fw.write(arr[i][j] + " ");
}
fw.write(" ");
}
fw.close();
}catch(Exception e){System.out.println(e);}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.