Skip to content

Instantly share code, notes, and snippets.

@basamoahjnr
Last active August 13, 2019 17:34
Show Gist options
  • Save basamoahjnr/cf4f1bfa39f6535b6115845825a105d5 to your computer and use it in GitHub Desktop.
Save basamoahjnr/cf4f1bfa39f6535b6115845825a105d5 to your computer and use it in GitHub Desktop.
package com.matrix.calculator;
import java.io.*;
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
// write your code here
System.out.println("Please Enter nine digits separated by spaces to construct your matrix: ");
Scanner scanner = new Scanner(System.in);
//true because we want to append to what ever is in the file already
var fileName = "matrix.txt";
writeMatrixFile(scanner, fileName);
readMatrixFile(fileName);
}
private static void writeMatrixFile(Scanner scanner, String fileName) {
try (FileWriter writer = new FileWriter(fileName, true); BufferedWriter bufferedWriter = new BufferedWriter(writer)) {
String[] user_input = scanner.nextLine().strip().split(" ");
for (int i = 0; i < user_input.length; i++) {
final int integer = Integer.valueOf(user_input[i].trim());
if (i == 3 | i == 6 | i == 9) {
bufferedWriter.newLine();
}
bufferedWriter.write(integer + " ");
}
} catch (IOException ignored) {
}
}
private static void readMatrixFile(String fileName) {
int[][] user_input_ = new int[3][3];
try (FileReader reader = new FileReader(fileName); BufferedReader bufferedReader = new BufferedReader(reader);
FileWriter writer = new FileWriter(fileName, true); BufferedWriter bufferedWriter = new BufferedWriter(writer)) {
String line;
int i = 0;
while ((line = bufferedReader.readLine()) != null && !line.isEmpty() && !line.isBlank()) {
String[] lineSplit = line.strip().split(" ");
for (int j = 0; j < lineSplit.length; j++) {
user_input_[i][j] = Integer.valueOf(lineSplit[j].trim());
}
i++;
}
int difference = (user_input_[0][0] * user_input_[1][1] * user_input_[2][2])
- (user_input_[0][2] * user_input_[1][1] * user_input_[2][0]);
bufferedWriter.newLine();
bufferedWriter.write("difference : " + difference + " ");
bufferedWriter.newLine();
} catch (IOException ignored) {
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment