Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package don23;
- import java.io.*;
- import java.util.Scanner;
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
- public class Main {
- public static Scanner scan = new Scanner(System.in);
- static int getMatrixSize()
- {
- int order = 0;
- boolean IsNotCorrect;
- do
- {
- System.out.println("Введите порядок матрицы: ");
- IsNotCorrect = false;
- try
- {
- order = Integer.parseInt(scan.nextLine());
- }
- catch (Exception e)
- {
- IsNotCorrect = true;
- System.out.println("Порядок матрицы должен быть положительным числом.");
- }
- if (!IsNotCorrect && (((order < 1) || (order > 10000))))
- {
- System.out.println("Порядок матрицы должен принадлежать промежутку от 1 до 10000");
- IsNotCorrect = true;
- }
- } while (IsNotCorrect);
- return order;
- }
- static int getMatrixElement()
- {
- int element = 0;
- boolean IsNotCorrect;
- do
- {
- System.out.println("Введите элемент матрицы: ");
- IsNotCorrect = false;
- try
- {
- element = Integer.parseInt(scan.nextLine());
- }
- catch (Exception e)
- {
- IsNotCorrect = true;
- System.out.println("Элемент матрицы должен быть положительным числом.");
- }
- if (!IsNotCorrect && (((element < -2147000000) || (element > 2147000000))))
- {
- System.out.println("Элемент матрицы должен принадлежать промежутку от -2147000000 до 2147000000");
- IsNotCorrect = true;
- }
- } while (IsNotCorrect);
- return element;
- }
- static int[][] сreateMatrix(int order)
- {
- var matrix = new int[order][order];
- for (int i = 0; i < order; i++) {
- for (int j = 0; j < order; j++)
- matrix[i][j] = getMatrixElement();
- }
- return matrix;
- }
- static int calculateSumByCondition(int[][] matrix)
- {
- int sum = 0;
- int j = 0;
- for (int i = 0; i < matrix.length; i++)
- {
- j = 0;
- while ((j < matrix.length) && (i != j))
- {
- if (matrix[i][j] > 0)
- sum += matrix[i][j];
- j++;
- }
- }
- return sum;
- }
- static void printMatrix(int[][] matrix) {
- for (int i = 0; i < matrix.length; i++) {
- for (int j = 0; j < matrix.length; j++) {
- System.out.printf("%6d", matrix[i][j]);
- }
- System.out.println();
- }
- System.out.println();
- }
- static String getOutputDirectory()
- {
- String patho;
- boolean isIncorrect;
- isIncorrect = true;
- do
- {
- System.out.println("Введите директорию, в которую хотите сохранить результат:");
- patho = scan.nextLine();
- var file = new File(patho);
- if (file.exists())
- isIncorrect = false;
- else
- System.out.println("Такой директории не существует. Попробуйте ещё раз.");
- } while (isIncorrect);
- return patho;
- }
- static void printResultToFile(int[][] matrix, int sum) throws IOException {
- var patho = getOutputDirectory();
- FileWriter myWriter = new FileWriter(patho + "output.txt");
- myWriter.write("Для матрицы\n");
- for (int i = 0; i < matrix.length; i++)
- {
- for (int j = 0; j < matrix.length; j++)
- myWriter.write(String.format("%6d", matrix[i][j]));
- myWriter.write("\n");
- }
- myWriter.write("Сумма положительных элементов под главной диагональю = " + sum);
- myWriter.close();
- System.out.println("Ответ сохранен по указанному пути.");
- }
- static void workWithConsole() throws IOException {
- int size = getMatrixSize();
- var matrix = сreateMatrix(size);
- printMatrix(matrix);
- int sum = calculateSumByCondition(matrix);
- System.out.println("Сумма положительных элементов под главной диагональю: " + sum);
- printResultToFile(matrix, sum);
- }
- static boolean isFileCorrect(String path) throws IOException {
- int num = 0;
- int totalCount = 0;
- boolean isCorrect;
- FileReader reader = new FileReader(path);
- Scanner scanner = new Scanner(reader);
- isCorrect = true;
- try
- {
- var size = scanner.nextInt();
- scanner.nextLine();
- while (scanner.hasNextLine() && isCorrect) {
- Matcher matcher = Pattern.compile("\\d+").matcher(scanner.nextLine());
- int iCount = 0;
- while (matcher.find()) {
- iCount++;
- totalCount++;
- }
- if (iCount != size && totalCount != size * size) {
- isCorrect = false;
- }
- }
- }
- catch(Exception e)
- {
- isCorrect = false;
- }
- reader.close();
- return isCorrect;
- }
- static String getMatrixFilePath() throws IOException {
- String path;
- boolean isIncorrect = true;
- do
- {
- System.out.println("Введите абсолютный путь к файлу: ");
- path = scan.nextLine();
- var mf = new File(path);
- if (!mf.exists())
- {
- System.out.println("Файл не найден. Проверьте введённый путь.");
- }
- else
- {
- if (isFileCorrect(path))
- isIncorrect = false;
- else
- System.out.println("Проверьте данные в файле. Это должны быть числа, записанные в виде матрицы. Порядок матрицы должен соответствовать введённому.");
- }
- } while (isIncorrect);
- return path;
- }
- static int[][] createMatrixFromFile(String path) throws FileNotFoundException {
- FileReader matrixFile = new FileReader(path);
- Scanner sc = new Scanner (matrixFile);
- var order = sc.nextInt();
- var matrix = new int[order][order];
- for (int i = 0; i < order; i++)
- for (int j = 0; j < order; j++)
- matrix[i][j] = sc.nextInt();
- return matrix;
- }
- static void workWithFile() throws IOException {
- var matrix = createMatrixFromFile(getMatrixFilePath());
- printMatrix(matrix);
- int sum = calculateSumByCondition(matrix);
- System.out.println("Сумма положительных элементов под главной диагональю: " + sum);
- printResultToFile(matrix, sum);
- }
- static void setProgramWorkType() throws IOException {
- int answer = 0;
- boolean isNotCorrect;
- do
- {
- System.out.println("1 - работать с консолью, 2 - с файлом: ");
- isNotCorrect = false;
- try
- {
- answer = Integer.parseInt(scan.nextLine());
- }
- catch (Exception e)
- {
- isNotCorrect = true;
- System.out.println("Введите число!");
- }
- if (!isNotCorrect && (((answer < 1) || (answer > 2))))
- {
- System.out.println("Выбирете один из предложенных вариантов!");
- isNotCorrect = true;
- }
- } while (isNotCorrect);
- if (answer == 1)
- workWithConsole();
- else
- workWithFile();
- }
- public static void main(String[] args) throws IOException {
- setProgramWorkType();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement