In java I want to have my output show up in a text file called \"output.txt\". T
ID: 668866 • Letter: I
Question
In java I want to have my output show up in a text file called "output.txt".
This is my print method for my array and it works as it should when it prints out in the console.
public void printArray(int matrix[][])
{
for (int row = 0; row < matrix.length; row++)
{
for (int column = 0; column < matrix[row].length; column++)
{
System.out.print(matrix[row][column] + " ");
}
System.out.println();
}
}
I would like to know what I need to do in this to make it to where I can have my output show up in the text file I create instead.
Explanation / Answer
=======================================
Program name WriteToFile.java
=======================================
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class WriteToFile {
public static void main(String[] args) {
int m, n;
Scanner sc = new Scanner(System.in);
System.out.print("Enter Number of rows :");
m = sc.nextInt();
System.out.print("Enter Number of columns :");
n = sc.nextInt();
// Declaring multi dimensional array with given dimensions
int array[][] = new int[m][n];
System.out.println("Enter matrix elements:");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
array[i][j] = sc.nextInt();
}
}
WriteToFile writer = new WriteToFile();
writer.printArray(array);
}
public void printArray(int matrix[][]) {
try {
FileWriter fileWriter = new FileWriter("output.txt");
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
bufferedWriter.write(matrix[row][column] + " ");
}
bufferedWriter.newLine();
}
bufferedWriter.close();
System.out.println("Writing data to output.txt completed");
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.