3일만에? 코딩 해보았다. 음.. 블로그를 작성해야 하니 꾸준히 할수밖에 없는(?) 시스템 참 좋은거 같다! 앞으로도 계속 아자아자 하면서 열심히 해보자구~! 히힛
저번에 이어서 ArrayList부터 시작된다. ArrayList를 declare하고 <>안에 type을 넣어야 하는데 이때 primitive type (int, double, boolean, etc..)는 들어갈수가 없고 class만 들어갈수 있다! 그래서 line 31은 <>안에 int가 명시되있으므로 에러가 뜬다. 하지만 int 혹은 double 같은 primitive type들을 ArrayList안에 넣을수 있는 방법이 있는데! 그건 바로 Integer || Double 과 같은 클래스를 넣는것이다. 이 클래스들안에 value는 같은 primitive type이지만 클래스 안에 집어 넣음으로 ArrayList에 하나의 타입으로도 쓸수 있는 것이다!
이런 클래스들을 Wrapper Class라고 하는데 https://www.w3schools.com/java/java_wrapper_classes.asp 에 보면 자세하게 나와있다.
오늘의 Challenge
// You job is to create a simple banking application.
// There should be a Bank class
// It should have an arraylist of Branches
// Each Branch should have an arraylist of Customers
// The Customer class should have an arraylist of Doubles (transactions)
// Customer:
// Name, and the ArrayList of doubles.
// Branch:
// Need to be able to add a new customer and initial transaction amount.
// Also needs to add additional transactions for that customer/branch
// Bank:
// Add a new branch
// Add a customer to that branch with initial transaction
// Add a transaction for an existing customer for that branch
// Show a list of customers for a particular branch and optionally a list
// of their transactions
// Demonstration autoboxing and unboxing in your code
// Hint: Transactions
// Add data validation.
// e.g. check if exists, or does not exist, etc.
// Think about where you are adding the code to perform certain actions
오늘 challenge를 진행 하면서 만들어야하는 클래스가 3개나 있고 각 클래스안에 다른 클래스 타입을 가지고 있는 ArrayList를 만들어야했기때문에 서로의 관계를 잘 이해하고 코드를 짜야해서 조금 생각을 많이 해야했던 challenge였던거 같다.
package demo;
import java.util.ArrayList;
public class Customer {
private String name;
private ArrayList<Double> dal = new ArrayList<Double>();
public Customer(String name, double initialAmount) {
this.name = name;
dal.add(Double.valueOf(initialAmount));
}
public String getName() {
return name;
}
public void addTransaction(double deposit) {
if(deposit<=0) {
System.out.println("Deposit amount invalid!");
return;
}
dal.add(Double.valueOf(deposit));
System.out.println("Deposit Successful!");
}
}
첫번째로 만들어야했던 Customer 클래스 인데 별다른건 없다. 다만 한가지 궁금증이 생겼던건 ArrayList를 굳이 constructor 안에서 initialize 하지 말고 그냥 애초에 declare할때 같이 initilize 하면 안되나?란 생각이 들어서 그냥 해버렸다. 한가지 이번에 배운 autoboxing을 addTransaction 메소드 안에 넣었는데 Double.valueOf(*primitive value*) 를 넣으면 된다.
package demo;
import java.util.ArrayList;
import java.util.Scanner;
public class Branch {
private String name;
private ArrayList<Customer> cal = new ArrayList<Customer>();
private static Scanner scan = new Scanner(System.in);
public Branch(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ArrayList<Customer> getCustomer(){
return cal;
}
public boolean addCustomer(String name, double initialAmount) {
Customer newCustomer = new Customer(name, initialAmount);
if(!queryCustomer(newCustomer)) {
cal.add(newCustomer);
System.out.println("New Customer has been added!");
return true;
} else {
System.out.println("Customer already exists!");
return false;
}
}
public boolean addCustomer(Customer customer) {
if(!queryCustomer(customer)) {
cal.add(customer);
System.out.println("New Customer has been added! ---> " + customer.getName());
return true;
} else {
System.out.println("Customer already exists!");
return false;
}
}
public boolean depositMoney(Customer customer) {
if(!queryCustomer(customer)) {
System.out.println("Customer does not exsit");
return false;
}
System.out.println("Enter the amount you wish to deposit: ");
boolean isDouble = scan.hasNextDouble();
while(true) {
if(!isDouble) {
System.out.println("Enter the proper amount: ");
isDouble = scan.hasNextDouble();
} else {
double deposit = scan.nextDouble();
int index = cal.indexOf(customer);
cal.get(index).addTransaction(deposit);
scan.nextLine();
break;
}
}
return true;
}
public boolean queryCustomer(Customer customer) {
return (cal.indexOf(customer)>=0) ? true : false;
}
}
두번째 Branch 클래스에서는 Customer ArrayList에 추가하는 기능이 있는데 queryCustomer이란 메소드를 만들어서 추가하기전 항상 존재하는 customer인지 확인하는 validation 절차를 걸쳤다. Challenge Instruction에는 customer를 추가할때 parameter에 대한 지시사항은 없었으므로 customer object & 이름, 시작금액 를 가진 두개의 메소드를 만들었다. 그다음으로는 depositMoney 라는 메소드가 있는데 여기서는 Scanner 클래스를 사용해서 유저로 하여금 직접 금액을 입력하게 하였으며 적절한 input을 넣지 않았을 경우를 대비 hasNextDouble()메소드를 사용해서 validation 단계를 걸치게 하였다.
package demo;
import java.util.ArrayList;
import java.util.Scanner;
public class Bank {
private String name;
private ArrayList<Branch> bal = new ArrayList<Branch>();
public Bank(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean addBranch(Branch branch) {
if(queryBranch(branch)) {
System.out.println("Branch already exists");
return false;
}
System.out.println("Branch has been successfully added! ---> " + branch.getName());
return true;
}
public boolean addCustomer(Branch branch, String name, double deposit) {
if(!queryBranch(branch)) {
System.out.println("Branch does not exist");
return false;
}
int index = bal.indexOf(branch);
bal.get(index).addCustomer(name, deposit);
return true;
}
public boolean addTransaction(Branch branch, Customer customer) {
if((!queryBranch(branch)) || (!branch.queryCustomer(customer))) {
System.out.println("Invalid branch or customer");
return false;
}
int branchIndex = bal.indexOf(branch);
if(bal.get(branchIndex).depositMoney(customer)) {
return true;
} else {
return false;
}
}
public void showListofCustomers(Branch branch) {
System.out.println("Selected branch is " + branch.getName());
System.out.println("\nThe names of customers are ---> ");
branch.getCustomer().forEach(customer -> {
System.out.print(customer.getName() + " -- ");
});
System.out.println("\nWould you like to make a transaction? 1 - yet, 2 - no\n");
Scanner scan = new Scanner(System.in);
int answer = scan.nextInt();
scan.nextLine();
switch(answer) {
case 1: System.out.println("Select the name of the customer: ");
String nameOfCustomer = scan.nextLine();
branch.getCustomer().forEach(customer -> {
if(customer.getName().equals(nameOfCustomer)) {
System.out.println("Enter the transaction amount: ");
double input = scan.nextDouble();
customer.addTransaction(input);
return;
}
});
break;
case 2: System.out.println("You enterd 2. Good bye");
break;
}
scan.close();
}
public boolean queryBranch(Branch branch) {
return (bal.indexOf(branch)>=0) ? true : false;
}
}
마지막 클래스인 Bank 클래스이다. 저번에 했던 challenge 또한 위에 Branch 클래스랑 비슷하게 branch를 추가하고 validate하는 메소드가 있다. showListofCustomers 메소드에서 forEach 메소드를 사용하였는데 이번에 알게된것이 "( -> {} )" 이 lambda expression 안에서 {}에는 statement가 들어갈수 없고 expression만 들어갈수 있다는 점이였다. 다른말로 하면 return ** 와 같은 statement는 들어갈수 없다는것이였다. https://www.baeldung.com/foreach-java
Guide to the Java 8 forEach | Baeldung
A quick and practical guide to Java 8 forEach
www.baeldung.com
여길 참조 하면 좋을거같다. 또한 switch statement를 사용하였는데 이번에 사용하면서 다시 한번 공부할수 있는 기회가 되서 좋았던거 같다. 예를 들어 각 case expression 후에 break를 붙여주지 않는다면 모든 case의 코드가 run 된다는거 + default는 그 어느 case에 해당하지 않은경우에 run되는 코드블럭이라는걸 다시 한번 review하였다.
04-02 switch/case 문
switch/case 문은 if 문과 비슷하지만 좀 더 정형화된 조건 판단문이다. switch/case 문의 구조는 다음과 같다. ```{.java} switch(입력변 ...
wikidocs.net
느낀점
오늘 주제는 autoboxing & unboxing이였지만 실질적으로 autoboxing은 한번밖에 쓰지 않았고 unboxing은 아예 쓰지 않았다.ㅎㅎ 하지만 개념은 이해하였고 syntax도 알고있으니 크게 문제 되지는 않을거같다. 오늘 challenge는 3개의 클래스의 관계를 잘 생각하여서 코드를 짜야했고 아직 많이 부족하지만 그래도 코딩을 하면서 즐거운시간이였다. 앞으로도 계속 꾸준히 연습하고 발전해 나가자~! 오늘도 코딩하시는 모든 코더분들 화이팅입니다!!
'테크스토리' 카테고리의 다른 글
자바 제네릭(Generic) 공부 후기 (0) | 2022.10.22 |
---|---|
Interface & Abstract Class 첼린지 후기 (0) | 2022.10.21 |
LinkedList 자신있으면 도전해봐~ (LinkedList Challenge 후기) (2) | 2022.10.11 |
*LinkedList* 어디까지 알고있니? (feat. Iterator & ConcurrentModificationException) (2) | 2022.10.08 |
ArrayList 같이 공부해요! (feat. Lambda Expression & Ternary Operator) (0) | 2022.10.03 |
댓글