public JButton transferAmountButton(Account sender, JTextField receiverAccountNumberTextField, JTextField transferAmountTextField, JLabel waringLabel) {
JButton transferButton = new JButton("송금");
transferButton.addActionListener(event -> {
String transferAmountText = transferAmountTextField.getText();
if (!transferAmountText.isEmpty() && transferAmountText.matches("\\d+")) {
int transferAmount = Integer.parseInt(transferAmountText);
String receiverAccountNumber = receiverAccountNumberTextField.getText();
for (Account receiverAccount : accountRepository) {
if (!receiverAccount.getAccountNumber().equals(receiverAccountNumber)) {
waringLabel.setText("계좌번호를 다시 확인 바랍니다.");
waringLabel.setForeground(Color.red);
}
if (receiverAccount.getAccountNumber().equals(receiverAccountNumber)) {
receiver = receiverAccount;
waringLabel.setText("송금을 완료했습니다.");
waringLabel.setForeground(Color.black);
break;
}
}
sender.transfer(receiverAccountNumber, receiver, transferAmount);
}
});
return transferButton;
}
마카오 뱅크 만들 때 항상 잘됐었는데 이번에 네명의 계좌를 관리하는 은행시스템을 만들다보니 오류가 좀 있었다.
가장 크게 해맸던 것은 int transferAmount = Integer.parseInt(transferAmountText);부분에서 평소에는 작성하고 그냥 넘어가는데 이번에는 계속해서 Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: ""라 뜨면서 Integer.parseInt(transferAmountText)이 부분이 null 값이라고 뜨는 것이다. 처음 겪는 상황이라 당황했다.
NumberFormatException은 문자열을 숫자로 변환하는 과정에서 예외가 발생하는 경우에 발생한다. JTextField에서 입력한 값을 숫자로 변환하려고 하면 입력한 값이 숫자가 아니라면 이 예외가 발생할 수 있다.
그러나 숫자를 입력하였음에도 불구하고 NumberFormatException이 발생하는 경우에는 대개 숫자를 문자열로 처리하는 과정에서 생기는 문제 때문이라는데 아무리 수정해도 바뀌지 않았다.
그러던중 입력받은 값이 비어 있지 않고, 숫자로 이루어져 있느지 확인하는 조건문을 찾게돼 적용해 보았다. 즉, 위에 코드에서 transferAmountTextField에 숫자가 입력되지 않은 경우에는 조건문 안으로 진입하지 않는다는 것이다.
if (!transferAmountText.isEmpty() && transferAmountText.matches("\\d+")) {를 써보니 null값이 안뜨고 계속해서 진행 할 수 있었다.
if (!transferAmountText.isEmpty() && transferAmountText.matches("\\d+")) {
// 이 조건문이 참일 때 실행될 코드
}
이 조건문은 두 가지 조건을 모두 만족해야 실행되는 조건문이다.
첫 번째 조건 !transferAmountText.isEmpty()은 transferAmountText 변수가 비어 있지 않은지를 확인하는 것이다. ! 연산자는 뒤에 오는 표현식이 참이 아닐 때 참을 반환하므로, transferAmountText가 비어 있지 않으면 참이 된다..
두 번째 조건 transferAmountText.matches("\\d+")은 transferAmountText 변수가 숫자로 이루어져 있는지를 확인하는 것이다. matches() 메소드는 정규표현식과 일치하는지를 확인하는 메소드이며, \\d+는 1개 이상의 숫자를 나타내는 정규표현식이다. 따라서 transferAmountText가 숫자로 이루어져 있으면 참이 된다.
예를 들어, 사용자가 이체할 금액을 입력하는 transferAmountTextField에 "10000"이라는 값을 입력했다면, 이 조건문은 참이 되어 내부 코드가 실행될 것이다. 하지만 만약 transferAmountTextField에 아무 값도 입력하지 않았거나, 문자를 입력했다면 이 조건문은 거짓이 되어 내부 코드가 실행되지 않는다.
'TIL' 카테고리의 다른 글
Day34(반복문을 사용하는 경우) (0) | 2023.03.07 |
---|---|
Day33(자바 컴파일 순서,반복의 3요소, 라이브러리와 framework차이, 객체지향 프로그램과 절차적 프로그램의 차이를 캡슐화 개념을 통해 설명,Value Object와 entity의 차이 ) (0) | 2023.03.06 |
Day31(객체지향 프로그래밍,생성자,오퍼레이션,결합도,List와ArrayList차이점,구현체,인터페이스) (0) | 2023.03.04 |
Day30(예약어,List,Class,생성자,this,도메인 모델, 상속,위임,오버로딩,라이브러리) (0) | 2023.03.03 |
Day29(객체지향 프로그램 작성에 대한 방향성,TDD 작성시 생각할 점,참조) (0) | 2023.03.02 |