JAVA/TermProject

자바 GUI 텀프 '행렬식과 역행렬 계산기' - 공부하는 도비

DOVISH WISDOM 2023. 6. 18. 12:24  
728x90
반응형

자바 GUI를 활용한 행렬식과 역행렬 계산기입니다.

초기 화면

행렬 크기를 입력후, 그 크기에 맞게 행렬 요소를 입력해주면

그에 따른 역행렬이 계산됩니다.

아래 처럼 숫자가 아닌 문자를 입력했을 땐, 역행렬이 계산되지 않습니다.

만약, 아래와 같은 오류 메시지를 출력하기 싫다면 에러 처리를 해주시면 됩니다. 

또한, 역행렬이 없는 행렬이 입력되면

"역행렬이 존재하지 않습니다."가 추가로 출력됩니다. 

 

아래에 전체 코드를 첨부해두겠습니다. 

Matrix.java.txt
0.01MB

 

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Matrix extends JFrame implements ActionListener {
    private JTextField sizeField;
    private JTextArea matrixArea;
    private JTextArea resultArea;

    public Matrix() {
        setTitle("행렬식과 역행렬 계산기");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        // 입력 패널
        JPanel inputPanel = new JPanel(new FlowLayout());
        JLabel sizeLabel = new JLabel("행렬의 크기와 행렬 요소를 입력하세요.");
        sizeLabel.setFont(new Font(Font.MONOSPACED,Font.PLAIN,18));
        sizeField = new JTextField(5);
        inputPanel.add(sizeLabel);
        inputPanel.add(sizeField);
        add(inputPanel, BorderLayout.NORTH);

        // 행렬 및 결과 패널
        JPanel centerPanel = new JPanel(new GridLayout(1, 2));

        // 행렬 입력 패널
        JPanel matrixPanel = new JPanel(new BorderLayout());
        matrixArea = new JTextArea();
        matrixArea.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 18));
        
        
        JScrollPane matrixScrollPane = new JScrollPane(matrixArea);
        matrixScrollPane.setBorder(BorderFactory.createEmptyBorder());
        matrixPanel.add(matrixScrollPane, BorderLayout.CENTER);
        matrixPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 5));
        matrixPanel.setBackground(Color.WHITE);
        matrixPanel.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY, 2));
      
        
        centerPanel.add(matrixPanel);

        // 결과 텍스트 영역
        resultArea = new JTextArea();
        resultArea.setEditable(false);
        resultArea.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 16));
        
        JScrollPane resultScrollPane = new JScrollPane(resultArea);
        resultScrollPane.setBorder(BorderFactory.createEmptyBorder()); // 스크롤 패널의 테두리 제거
        resultScrollPane.setBorder(BorderFactory.createEmptyBorder(10, 5, 10, 10)); // 외부 여백 추가
        resultScrollPane.setBackground(Color.WHITE); // 배경색 설정
        resultScrollPane.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY, 2)); // 테두리 추가 

        centerPanel.add(resultScrollPane);

        add(centerPanel, BorderLayout.CENTER);

        // 계산 버튼
        JButton calculateButton = new JButton("Calculate");
        calculateButton.addActionListener(this);
        calculateButton.setBackground(Color.GRAY);
        calculateButton.setForeground(Color.white);
        calculateButton.setFont(new Font("SansSerif",Font.BOLD,16));
        add(calculateButton, BorderLayout.SOUTH);
        
        
        setSize(500, 400);
        setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getActionCommand().equals("Calculate")) {
            int size = Integer.parseInt(sizeField.getText());
            
            double[][] matrix = new double[size][size];
            String[] lines = matrixArea.getText().split("\n");
            for (int i = 0; i < size; i++) {
                String[] values = lines[i].split(" ");
                for (int j = 0; j < size; j++) {
                    matrix[i][j] = Double.parseDouble(values[j]);
                }
            }

            double[][] inverseMatrix = invert(matrix);
            double det = Determinant(matrix);

            // 결과 표시
            StringBuilder result = new StringBuilder();
            if (det == 0)
            {
            	result.append("Det  <A>  :   ").append(det).append("\n");
            	result.append("역행렬이 존재하지 않습니다.\n\n");
            }
            else {
            	result.append("Det  <A>  :   ").append(det).append("\n\n");
            }
            

            result.append("역행렬 : \n");
            for (int i = 0; i < size; i++) {
                for (int j = 0; j < size; j++) {
                    result.append(String.format("%.3f\t", inverseMatrix[i][j]));
                }
                result.append("\n");
            }
            resultArea.setText(result.toString());
        }
    }

    public static double Determinant(double a[][]) {
        int n = a.length;
        double det = 0;

        if (n == 1) {
            det = a[0][0];
        } else if (n == 2) {
            det = a[0][0] * a[1][1] - a[0][1] * a[1][0];
        } else {
            det = 0;
            int sign = 1;
            for (int i = 0; i < n; i++) {
                double[][] subMatrix = new double[n - 1][n - 1];
                for (int j = 1; j < n; j++) {
                    int subMatrixCol = 0;
                    for (int k = 0; k < n; k++) {
                        if (k == i) {
                            continue;
                        }
                        subMatrix[j - 1][subMatrixCol] = a[j][k];
                        subMatrixCol++;
                    }
                }
                det += sign * a[0][i] * Determinant(subMatrix);
                sign = -sign;
            }
        }

        return det;
    }

    public static double[][] invert(double a[][]) {
        int n = a.length;
        double[][] augmentedMatrix = new double[n][2 * n];

        // Augmented matrix 생성
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                augmentedMatrix[i][j] = a[i][j];
            }
            augmentedMatrix[i][i + n] = 1;
        }

        // 가우스-조단 소거법
        for (int i = 0; i < n; i++) {
            double pivot = augmentedMatrix[i][i];
            for (int j = 0; j < 2 * n; j++) {
                augmentedMatrix[i][j] /= pivot;
            }
            for (int k = 0; k < n; k++) {
                if (k != i) {
                    double factor = augmentedMatrix[k][i];
                    for (int j = 0; j < 2 * n; j++) {
                        augmentedMatrix[k][j] -= factor * augmentedMatrix[i][j];
                    }
                }
            }
        }

        // 역행렬 추출
        double[][] inverseMatrix = new double[n][n];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                inverseMatrix[i][j] = augmentedMatrix[i][j + n];
            }
        }

        return inverseMatrix;
    }

    public static void main(String[] args) {
        new Matrix();
    }
}
반응형