오늘은 Motivation 프로그램을 만드는 걸 해볼거야! 아직 우리가 배운건 자바 뿐이니... 자바 콘솔창을 이용해서 프로그램을 짜보자
일단 어떻게 구성을 할 것인지 생각을 해야하는데, 먼저 내가 생각거는 CRUD를 이용하고,
그리고 목록보여주기 정도로 생각했어.
-그러면 먼저 제일 쉬운 종료, 등록, 목록을 만들어 보자
import java.util.Scanner;
public class App {
private Scanner sc;
public App(Scanner sc) {
this.sc = sc;
}
public void run() {
System.out.println("== motivation 실행 ==");
int lastId = 1;
while (true) {
System.out.print("명령어) ");
String cmd = sc.nextLine().trim();
if (cmd.equals("exit")) {
System.out.println("== motivation 종료 ==");
break;
} else if (cmd.length() == 0) {
System.out.println("명령어가 입력되지 않았음");
continue;
}
if (cmd.equals("add")) {
System.out.print("motivation : ");
String motivation = sc.nextLine();
System.out.print("source : ");
String source = sc.nextLine();
System.out.printf("%d번 motivation이 등록됨\n", lastId);
lastId++;
}else if(cmd.equals("list")) {
System.out.println("=".repeat(40));
System.out.printf(" 번호 / source / motivation \n");
}
}
}
}
우리가 이제 또 생각해 봐야 할게 계속 add를 하면 데이터가 쌓일거 아니야?
이거를 어디에 저장하고 관리할까 이거야. 그래서 우리는 ArrayList를 이용해서 관리를 해보도록 할게.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class App {
private Scanner sc;
public App(Scanner sc) {
this.sc = sc;
}
public void run() {
System.out.println("== motivation 실행 ==");
int lastId = 0;
List<Motivation> motivations = new ArrayList<Motivation>();
while (true) {
System.out.print("명령어) ");
String cmd = sc.nextLine().trim();
if (cmd.equals("exit")) {
System.out.println("== motivation 종료 ==");
break;
} else if (cmd.length() == 0) {
System.out.println("명령어가 입력되지 않았음");
continue;
}
if (cmd.equals("add")) {
int id = lastId + 1;
System.out.print("body : ");
String body = sc.nextLine();
System.out.print("source : ");
String source = sc.nextLine();
Motivation motivation = new Motivation(id, body, source);
motivations.add(motivation);
System.out.printf("%d번 motivation이 등록됨\n", id);
lastId++;
} else if (cmd.equals("list")) {
System.out.println("=".repeat(40));
System.out.printf(" 번호 / source / motivation \n");
if (motivations.size() == 0) {
System.out.println("등록된 moti 없어");
} else {
System.out.println("1개 이상 있음");
}
System.out.println("=".repeat(40));
}
}
}
}
class Motivation {
int id;
String body;
String source;
public Motivation(int id, String body, String source) {
this.id = id;
this.body = body;
this.source = source;
}
@Override
public String toString() {
return "Motivation{" +
"id=" + id +
", body='" + body + '\'' +
", source='" + source + '\'' +
'}';
}
}
Motivation motivation = new Motivation(id, body, source); 먼저 motivation 객체를 만들어서 id,body,source 매개변수를 Motivation클래스랑 연결 시켜줘서 데이터들을 관리 할 생각이야.
ArrayList를 이용해서 add할때 마다 저장되는 공간을 만들어 줄거야.
그리고 Motivation클래스를 만들어서 id, body, source 변수를 여기에 선언하면motivation.add 이런식으로 motivation객체를 이용해 Motivation클래스에 정의된 변수들에게 쉽게 접근이 가능하고, add함수를 이용해 ArrayList에 있는 값을 추가 하는 함수를 이용해 사용자가 입력한 데이터들을 추가하도록 구현했어. 이러면 우리가 데이터를 추가시키고 싶을때 마다 add라는 명령어를 입력해서 손쉽게 추가 할 수 있잖아? 완전 대박이지?