JAVA
[JAVA] 예제 - ArrayList를 이용하여 학생부 프로그램 만들기
yn98
2024. 7. 15. 17:25
예전에 학생부 프로그램을 예제로 만들어 본 적이 있었다.
JAVA 함수를 이용해서 학생부 프로그램 만들기
아래는 함수를 이용하지 않고 MAIN에다가 전부 입력해서 프로그램을 만들어놓은 예시이다.import java.util.Scanner;public class Test01 { public static void main(String[] args) { String[] datas = new String[5]; Scanner sc=new Sc
yn98.tistory.com
지금은 이전보다 배운 개념이 많아서 다시 만들어보았다.
package class05;
import java.util.ArrayList;
import java.util.Scanner;
class Student {
private int num;
private String name;
private int score;
Student(int num, String name, int score){
this.num = num;
this.name = name;
this.score = score;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
@Override
public String toString() {
return "Student [num=" + num + ", name=" + name + ", score=" + score + "]";
}
}
public class Test01 {
public static boolean isListEmpty(ArrayList<Student> datas) { // 리스트가 비어있니?
if(datas.isEmpty()) {
System.out.println("출력할 데이터가 없습니다!");
return true; // 리스트가 비어있음
}
return false; // 리스트가 비어있지 않음
}
public static void addStudent(ArrayList<Student> datas, int PK, Scanner sc) { // 1번 - 학생추가 함수
System.out.println("이름입력 >> ");
String name = sc.next();
System.out.println("성적입력 >> ");
int score = sc.nextInt();
datas.add(new Student(PK++, name, score));
System.out.println("학생 데이터 추가 완료!");
}
public static void printAll(ArrayList<Student> datas) { // 2번 메뉴 - 전체출력
if (isListEmpty(datas)) // 유효성 검사
return;
for(Student data:datas) {
System.out.println(data);
}
}
public static void searchPK(ArrayList<Student> datas, Scanner sc) { // 3번 메뉴 - 번호검색
if (isListEmpty(datas)) // 유효성 검사
return;
System.out.print("번호입력 >> ");
int num=sc.nextInt();
Student data=hasStudent(datas,num);
if(data != null) {
System.out.println("[검색결과]");
System.out.println(data);
}
else {
System.out.println("검색 결과가 없음!");
}
}
public static void searchName(ArrayList<Student> datas, Scanner sc) { // 4번 메뉴 - 이름검색 == selectAll
if (isListEmpty(datas)) // 유효성 검사
return;
System.out.print("검색어입력 >> ");
String searchKeyword=sc.next();
ArrayList<Student> al=hasStudent(datas,searchKeyword);
if(al.size() <= 0) {
System.out.println("검색 결과가 없음!");
return;
}
System.out.println("[검색결과]");
for(Student s:al) {
System.out.println(s);
}
}
public static void printAvg(ArrayList<Student> datas) { // 5. 평균출력
if (isListEmpty(datas)) // 유효성 검사
return;
int sumSc = 0; // 점수 합 구하기
for(Student data : datas) {
sumSc += data.getScore();
}
double avgSc = sumSc * 1.0 / datas.size(); // double로 출력되도록.
System.out.println("평균 점수: "+avgSc);
}
public static void changeScore(ArrayList<Student> datas, Scanner sc) { // 6번 - 점수 변경
if (isListEmpty(datas)) // 유효성 검사
return;
System.out.print("변경하고 싶은 학생의 학번을 입력해주세요. >> ");
int num = sc.nextInt();
Student data=hasStudent(datas,num);
if(data == null) {
System.out.println("검색 결과가 없음!");
return;
}
System.out.print("성적입력 >> ");
int score=sc.nextInt();
data.setScore(score);
System.out.println("변경완료!");
}
public static void deleteStudent(ArrayList<Student> datas, Scanner sc) { // 7번 - 학생 삭제
if (isListEmpty(datas)) // 유효성 검사
return;
System.out.print("번호입력 >> ");
int num=sc.nextInt();
boolean flag=false;
for(int i=0;i<datas.size();i++) {
if(datas.get(i).getNum() == num) {
flag=true;
datas.remove(i);
break;
}
}
if(!flag) {
System.out.println("검색 결과가 없음!");
}
/*
Student data=hasStudent(datas,num);
if(data == null) {
System.out.println("검색 결과가 없음!");
continue;
}
for(int i=0;i<datas.size();i++) {
if(datas.get(i).getNum() == data.getNum()) {
datas.remove(i);
break;
}
}
*/
else {
System.out.println("잘못된 입력입니다!");
}
}
public static Student hasStudent(ArrayList<Student> datas,int num) { // 학생이 있니?
for(Student data:datas) {
if(num == data.getNum()) {
return data;
}
}
for(int i=0;i<datas.size();i++) {
if(num == datas.get(i).getNum()) {
return datas.get(i);
}
}
return null;
}
public static ArrayList<Student> hasStudent(ArrayList<Student> datas,String searchKeyword) { // 학생"들"이 있니?
ArrayList<Student> al=new ArrayList<Student>();
// 1. 반환할 배열을 생성
for(Student data:datas) {
if(data.getName().contains(searchKeyword)) {
// 2. 이름에 keyword가 들어가있다면,
al.add(data);
// 3. 반환할 배열에 저장
}
}
return al;
// 4. 반환
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<Student> datas = new ArrayList<Student>();
// 배열 역할을 하는 컬렉션 배열리스트
// 학생부 역할
// [샘플 데이터 생성]
int PK = 1001; // 시스템에서 부여
datas.add(new Student(PK++, "홍길동", 50));
datas.add(new Student(PK++, "아무무", 88));
datas.add(new Student(PK++, "티모", 67));
// [전체출력]
// [학생추가]
while(true) {
System.out.println("=== 메 뉴 ===");
System.out.println("1. 학생추가");
System.out.println("2. 전체출력");
System.out.println("3. 번호검색");
System.out.println("4. 이름검색");
System.out.println("5. 평균출력");
System.out.println("6. 점수변경");
System.out.println("7. 학생삭제");
System.out.println("0. 프로그램 종료");
System.out.println("============");
System.out.print("메뉴입력 >> ");
int action = sc.nextInt();
if(action == 0) {
sc.close();
break;
}
else if(action ==1) { // 학생추가
addStudent(datas, PK, sc);
}
else if(action ==2) { // 전체출력
printAll(datas);
}
else if(action==3) { // 번호검색 == PK로 검색 == selectOne
searchPK(datas, sc);
}
else if(action ==4) { // 이름검색 == selectAll
searchName(datas, sc);
}
else if(action ==5) { // 평균출력
printAvg(datas);
}
else if(action ==6) { // 점수변경
changeScore(datas, sc);
}
else if(action ==7) { // 학생삭제
deleteStudent(datas, sc);
}
else {
System.out.println("잘못 입력했습니다. 다시 입력해주세요!");
continue;
}
}
}
}
코드를 최대한 많이 재사용하려고 노력했다. 또한 접근 제어자랑 toString()도 배웠기 때문에 활용해보았다.