(1-2) [Java] 학생관리 프로그램 만들기

씩씩한 조약돌·2022년 12월 25일
0

미니프로젝트🤹

목록 보기
1/21
package firstproject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Scanner;

첫화면 출력

✅ 프로그램 시작할 때 학생정보 초기화

public class Main {

	public static void main(String[] args) {
		
		//프로그램 처음 시작했을 때 학생정보 초기화시키기
		File file = new File("src/AInsert/student.txt");
		
		if(file.exists()) {
			file.delete();
		}

✅ while(true) 로 '5 종료' 전까지 무한반복 처리
-> '5 종료'는 break; / 나머지는 continue;로 변경

		//프로그램 시작
		while(true) {

			Scanner sc = new Scanner(System.in);

			System.out.printf(
					"##### 학생 관리 프로그램 #####\n"
							+ "1. 입력\n"
							+ "2. 보기\n"
							+ "3. 검색\n"
							+ "4. 수정\n"
							+ "5. 종료\n"
							+ "#########################\n\n"
					);

번호 입력

✅ scanner로 처리

			System.out.print("번호 입력 : ");
			int in = sc.nextInt();
			//		int in = 2;

switch문으로 1~5번 입력하면 이동

      
		
		switch(in) {
        

switch문 (1번 : 입력)

		
			/////1 입력///////////////////////////////////////
			case 1 : System.out.println("1. 입력"); 

폴더 생성

			// 폴더(AInsert) 없으면 생성
				File dir = new File("src/AInsert");
				
				if(!dir.isDirectory()) {
					dir.mkdir();
				}

파일(txt) 생성

			//파일(student.txt) 없으면 생성
				file = new File("src/AInsert/student.txt");

				if(! file.exists()) {
					try {
						file.createNewFile();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}//if

학생정보 입력

AInsert클래스 및 객체info생성해서 입력받은 값을 저장

생각해보기 -> 입력받은 값을 다음 줄에 추가하는 방법
(1) FileWriter / write() / flush()
: 파일에 한 줄 추가
(2) 🔅RandomAccessFile / seek() / writeBytes() / close()
: 원하는 위치에 입력 (seek으로 포인터를 파일 마지막으로 옮겨서 다음 값을 입력하고 싶었는데 -> 한글이 깨져서 입력되고, 줄바꿈이 안됨)


-> 2022.12.22내용추가

  • 입력받은 값 출력하고 종료로 변경
  • 한글깨짐 현상 수정해야함

AInsert클래스

: 입력받은 값을 모아서 toString()으로 txt파일에 한 줄로 입력하기 위한 용도

package firstproject;

public class AInsert {
	
	String name;
	String number;
	int ko;
	int en;
	int ma;
	
	public AInsert() {
		// TODO Auto-generated constructor stub
	}

	public AInsert(String name, String number, int ko, int en, int ma) {
		super();
		this.name = name;
		this.number = number;
		this.ko = ko;
		this.en = en;
		this.ma = ma;
	}
	
	@Override
	public String toString() {
		return String.format("%5s %8s %4d %4d %4d", name, number, ko, en, ma);
	}

}

			//정보 입력
				//FileWriter fw = null;
				RandomAccessFile fw = null;
				
				try {
					//fw = new FileWriter(file, true); //false = update
					
					System.out.print("이름 : ");
					String name = sc.next();
					System.out.print("학번 : ");
					String number = sc.next();
					System.out.print("국어 : ");
					int ko = sc.nextInt();
					System.out.print("영어 : ");
					int en = sc.nextInt();
					System.out.print("수학 : ");
					int ma = sc.nextInt();
							
					
					AInsert info = new AInsert(name, number, ko, en, ma);
					fw = new RandomAccessFile(file,"rw"); //"rw" : reading and write
					
					long size = fw.length();
					fw.seek(size);
					fw.writeBytes(info.toString());
					
					
					//fw.write(info.toString());
					//fw.flush();
					
					System.out.println(info);
					
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} finally {
					if(fw != null)
						try {
							fw.close();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
				}
				
				continue;
				///////////////////////////////////////////

switch문 (2번 : 출력)

✅출력 아주 잘 됨 (good)


-> 2022.12.22 내용추가
✅ 프로그램 실행 시 txt파일 초기화 처리해서 파일 변경
✅ 내용출력 후 줄바꿈 2번 추가

			/////2 보기///////////////////////////////////////
				case 2 : System.out.println("2. 보기"); 
				
				File filePrint = new File("src/AInsert/student.txt");
				FileReader fr = null;
				
				System.out.printf("%5s %6s %4s %4s %3s\n", "이름", "학번", "국어", "영어", "수학");
				
				try {
					fr = new FileReader(filePrint);
					
					for(long i = 0; i<filePrint.length(); i++) {
						
						try {
							System.out.print((char)fr.read());
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}//for				
					
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}			
				
				System.out.println();
				System.out.println();
				
				continue;
				///////////////////////////////////////////

switch문 (3번:검색)

생각중인 것 -> txt파일을 한 줄씩 읽어오는 방법
: split()으로 나눠서 string배열로 만들기
/ String배열[0]의 값은 name이 들어감
/ nameSearch(스캐너로 입력받은 이름)값과 [0]값 비교해서
//같으면 -> String배열 전체값 출력 -> 종료
//마지막줄까지 읽었는데 같은 이름이 없으면 / "잘못입력하셨습니다" -> 초기화면

			/////3 검색///////////////////////////////////////
			case 3 : System.out.println("3. 검색"); 
			
			System.out.print("이름 검색 : ");
			String nameSearch = sc.next();
			System.out.println(nameSearch);
	
			
			
			
			continue;
			///////////////////////////////////////////

switch문 (4번:수정)

			/////4 수정///////////////////////////////////////
			case 4 : System.out.println("4. 수정"); 
            continue;
			///////////////////////////////////////////

switch문 (5번:종료)

			/////5 종료///////////////////////////////////////
			case 5 : System.out.println("5. 종료"); 
			System.out.println("종료되었습니다.");
			
			break;
			///////////////////////////////////////////

switch문 (default : 번호 잘못 입력)

✅ "1~5사이 숫자만 입력해주세요" -> 다시 메뉴판 보여주기(처음으로 돌아가기)
✅ 5 종료 (break), switch문 끝나고 break; 해줘야함
-> break;는 가장 가까운 반복문을 빠져나감

			/////6 잘못 입력///////////////////////////////////////
				default : System.out.println("1~5사이 숫자만 입력해주세요");
				System.out.println();
				continue;
				//다시 처음으로 돌아가기->while문으로 처리
			}//end of switch
			
			break;
		}//end of while
		
	}//main

}//class

2일차 후기

  1. 첫번째 파일을 깃허브에 올렸다가 에러가 나서 프로젝트폴더를 새로 만들어서 클래스를 다시 작성했다. 깃허브 사용방법도 시행착오가 좀 더 필요할 것 같다.

  2. 오늘 목표는 while반복문 처리, 텍스트파일 초기화. 둘 다 ok.

  3. '1입력'에서 스캐너로 입력받은 값이 메모장으로 넘어가면 자꾸 한글이 깨진다.-> why?

  4. 스캐너가 실행중이면 프로그램 종료가 안됨. consol창에서 강제종료를 꼭 해줘야 나중에 프로그램이 엉키지 않음(ex. 프로그램이 깔끔하게 종료되지 않으면 txt파일이 초기화가 되지않음)

  5. 3검색 4수정은 방법을 좀 더 찾아봐야 할 것 같다.

profile
씩씩하게 공부중 (22.11~)

0개의 댓글