Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.FileWriter;
- import java.io.IOException;
- import java.util.Arrays;
- import java.util.Scanner;
- public class Main {
- static Scanner scanner = new Scanner(System.in);
- public static int size = 0;
- public static int[][] magicSquare;
- public static void main(String[] args) throws IOException {
- task();
- int num;
- do {
- getInfo();
- num = getNum();
- getUserChoice(num);
- } while (num != 0);
- scanner.close();
- }
- private static void task() {
- System.out.println("Разработать программу, которая генерирует магический квадрат чётно-нечётной степени (6, 10, 18, …).");
- }
- private static void getInfo() {
- System.out.println("""
- 1 - Показать магический квадрат\s
- 2 - Сохранить квадрат в файл\s
- 0 - Нажмите чтобы выйти""");
- }
- private static int getNum() {
- int num = 0;
- boolean isCorrect;
- do {
- isCorrect = true;
- System.out.print("Введите число: ");
- try {
- num = Integer.parseInt(scanner.nextLine());
- } catch (NumberFormatException e) {
- isCorrect = false;
- System.out.println("Проверьте корректность введенных данных");
- }
- if (isCorrect && (num < 0 || num > 3)) {
- isCorrect = false;
- System.out.println("Диапазон ввода размера от 0 до 2");
- }
- } while (!isCorrect);
- return num;
- }
- private static int getSize() {
- boolean isCorrect;
- do {
- isCorrect = true;
- System.out.print("Введите размер квадрата: ");
- try {
- size = Integer.parseInt(scanner.nextLine());
- } catch (Exception e) {
- isCorrect = false;
- System.out.println("Проверьте корректность введенных данных");
- }
- if (isCorrect && size <= 50) {
- if ((size % 2 == 0) && (size % 4 != 0)) {
- } else {
- System.out.println("Число должно быть четно-нечетной степени");
- isCorrect = false;
- }
- } else {
- System.out.println("Максимальный размер квадрата равен 50");
- }
- } while (!isCorrect);
- return size;
- }
- private static int[][] magicSquareOfOddOrder(int n) {
- int[][] matrix = new int[n][n];
- for (int i = 0; i < n; i++) {
- Arrays.fill(matrix[i], 0);
- }
- int count = 1, y = 0, x = matrix.length/2;
- do {
- matrix[y][x] = count;
- count++;
- if (((y == 0) && (x >= n - 1)) && (matrix[n - 1][0] != 0)) {
- y++;
- } else {
- y--;
- if (y < 0) {
- y = n - 1;
- }
- x++;
- if (x == n) {
- x = 0;
- }
- if (matrix[y][x] != 0) {
- y += 2;
- x--;
- }
- }
- } while (count != n * n + 1);
- return matrix;
- }
- private static int[][] magicSquareOfEvenOddOrder(int n) {
- int half = n/2;
- int[][] matrix = new int[n][n];
- int[][] tempMatrix;
- tempMatrix = magicSquareOfOddOrder(half);
- // 1/4 матрицы
- for (int i = 0; i < half; i++) {
- for (int j = 0; j < half; j++) {
- matrix[i][j] = tempMatrix[i][j];
- }
- }
- // 2/4 матрицы
- for (int i = 0; i < half; i++) {
- for (int j = half; j < n; j++) {
- int x = j-half;
- matrix[i][j] = (tempMatrix[i][x]+2*half*half);
- }
- }
- // 3/4 матрицы
- for (int i = half; i < n; i++) {
- for (int j = 0; j < half; j++) {
- int x = i-half;
- matrix[i][j] = (tempMatrix[x][j]+3*half*half);
- }
- }
- // 4/4 матрицы
- for (int i = half; i < n; i++) {
- for (int j = half; j < n; j++) {
- int x = i-half, y = j-half;
- matrix[i][j] = (tempMatrix[x][y]+half*half);
- }
- }
- int move = 0;
- for (int i = 6; i < n; i++) {
- if((i%4!=0)&&(i%2==0)) move++;
- }
- for (int j = matrix.length/2-move; j <= matrix.length/2+move-1; j++) {
- for (int i = 0; i < tempMatrix.length; i++) {
- int key = matrix[i][j];
- matrix[i][j] = matrix[half+i][j];
- matrix[half+i][j] = key;
- }
- }
- for (int j = 0; j <= 1; j++) {
- if (j == 0) {
- int key = matrix[0][0];
- matrix[0][0] = matrix[half][0];
- matrix[half][0] = key;
- }
- if (j == 1) {
- int key = matrix[half - 1][0];
- matrix[half - 1][0] = matrix[n - 1][0];
- matrix[n - 1][0] = key;
- }
- }
- for (int j = half+1; j < n-1; j++) {
- for (int i = 1; i < half-1; i++) {
- int key = matrix[i][1];
- matrix[i][1] = matrix[half+i][1];
- matrix[half+i][1] = key;
- }
- }
- return matrix;
- }
- private static int readingSelection() {
- boolean isCorrect;
- int number = 0;
- do {
- isCorrect = true;
- System.out.println("Хотите получить размер из файла - введите 0, ввести в консоли - 1");
- try {
- number = Integer.parseInt(scanner.nextLine());
- } catch (Exception e) {
- isCorrect = false;
- System.out.println("Проверьте корректность введенных данных");
- }
- if (isCorrect && (number < 0) || (number > 1)) {
- System.out.println("Введите 0 или 1");
- }
- } while (!isCorrect);
- return number;
- }
- private static String inputPath() {
- String path;
- boolean isCorrect;
- do {
- isCorrect = true;
- System.out.println("Введите полный путь к файлу");
- path = scanner.nextLine();
- File file = new File(path);
- if (!file.exists()) {
- isCorrect = false;
- System.out.println("Неверно введен путь");
- }
- if (isCorrect && !file.canRead()) {
- System.out.println("Невозможно считать данные с файла");
- }
- if (isCorrect && !file.canWrite()) {
- System.out.println("Невозможно записать данные в файл");
- }
- } while (!isCorrect);
- return path;
- }
- private static int openData() throws FileNotFoundException {
- String path = inputPath();
- boolean isCorrect = true;
- Scanner fileReader = new Scanner(new File(path));
- try {
- size = fileReader.nextInt();
- } catch (Exception e) {
- isCorrect = false;
- System.out.println("");
- }
- if (isCorrect && size <= 50) {
- if ((size % 2 == 0) && (size % 4 != 0)) {
- } else {
- System.out.println("Число должно быть четно-нечетной степени");
- isCorrect = false;
- }
- } else {
- System.out.println("Максимальный размер квадрата равен 50");
- isCorrect = false;
- }
- if (isCorrect) {
- System.out.println("Данные были успешно считаны.");
- } else {
- System.out.println("Данные не были считаны с файла");
- size = getSize();
- }
- return size;
- }
- private static void outputSquare() throws IOException{
- int number = readingSelection();
- if (number == 1) {
- size = getSize();
- } else {
- size = openData();
- }
- magicSquare = new int[size][size];
- if ((size % 2 == 0) && (size % 4 != 0)) {
- magicSquare = magicSquareOfEvenOddOrder(size);
- }
- for (int i = 0; i < size; i++) {
- for (int j = 0; j < size; j++) {
- System.out.print(magicSquare[i][j] + "\t");
- }
- System.out.println();
- }
- }
- private static void saveSquareToFile() throws IOException {
- if ((size % 2 != 0) || (size % 4 == 0)) {
- System.out.println("Создайте квадрта");
- return;
- }
- String path = inputPath();
- FileWriter writer = new FileWriter(path);
- for (int i = 0; i < size; i++) {
- for (int j = 0; j < size; j++) {
- writer.write(magicSquare[i][j] + "\t");
- }
- System.out.println();
- }
- writer.close();
- }
- private static void getUserChoice(int num) throws IOException {
- switch (num) {
- case 1 -> outputSquare();
- case 2 -> saveSquareToFile();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment