# 13. Java 12일차(230830) [국비교육]

brand_mins·2023년 8월 30일

Java

목록 보기
13/47
- 오늘 배운 프로그램 코드 한번 더 쳐보면서 학습
- 2번부터 프로그램들은 주말에 학습할 것.
- 2(6)은 HashMap 컬렉션 자료구조에서 다시 한번보기

1. 배열 관련 은행 프로그램 구현

public class BankArray {
	// final 키워드는 해당 데이터가 상수여서 변경 불가능.
	// 관용적으로 상수는 모두 대문자 사용하고 새로운 의미가 나올때마다 밑줄 사용함.
	// 상태를 수자로 사용하면 의미를 파악하기 어려워 문자상수 표현
	public static final int STATE_LOGOUT = 0;
	public static final int STATE_USER_LOGIN = 1;
	public static final int STATE_ADMIN_LOGIN = 2;
	public static final int STATE_EXIT = -1;
	// enum 자바문법	
	// 최대 저장할 수 있는 전체사용자(id, pw, account) 저장
	// 일반 사용자 목록 저장공간
	public static String id[] = new String[100];
	public static String pw[] = new String[100];
	public static double account[] = new double[100];
	// 일반 사용자 전체 갯수
	public static int totalUserCount = 0;
	// 로그인 한 사람의 인덱스
	public static int loginUserIndex = -1;
	// 로그인
	public static int loginUserStatus = BankArray.STATE_LOGOUT;	
	// 관리자면 loginUserIndex = -2 변경
	public static String adminId = "admin";
	public static String adminPw = "1234";	
	// 사용자 입력받기 위한 Scanner와 사용자입력을 처리할 변수들
	public static java.util.Scanner scanner = new java.util.Scanner(System.in);
	public static String inputId = null;
	public static String inputPw = null;
	public static double InputAccount = 0;	
		public static void main(String[] args) {
		// 초기화 작업: 일반 사용자 3명추가
			BankArray.id[0] = "user1";
			BankArray.pw[0] = "user1";
			BankArray.account[0] = 1000;
			BankArray.id[1] = "user2";
			BankArray.pw[1] = "user2";
			BankArray.account[1] = 2000;
			BankArray.id[2] = "user3";
			BankArray.pw[2] = "user3";
			BankArray.account[2] = 3000;			
			BankArray.totalUserCount = 3;
			// 로그인 작업
			while(BankArray.loginUserStatus != BankArray.STATE_EXIT) {
				System.out.println("아이디와 pw를 입력해주세요." + " 종료하고 싶다면 EXIT를 입력해주세요.");
				System.out.print("id입력> ");
				BankArray.inputId = scanner.nextLine();
				System.out.print("pw입력> ");
				BankArray.inputPw = scanner.nextLine();
			// 일반 사용자 로그인 시도	
			boolean isFindUser = false;
			for(int i=0; i<BankArray.totalUserCount; i++) {
				if(BankArray.id[i].equals(BankArray.inputId)) {
					if(BankArray.pw[i].equals(BankArray.inputPw)) {
						System.out.println(id[i] + "님 어서오세요.");
						BankArray.loginUserIndex = i;
						BankArray.loginUserStatus = BankArray.STATE_USER_LOGIN;
					} else {
						System.out.println("잘못된 id나 패스워드가 입력되었습니다.");
					}
					isFindUser = false;
					break;
				}
			}
			// i==BankArray.totalUserCount
			// 사용자가 입력한 아이디가 기존 일반 사용자 아이디에 존재하지 않음.
			if(!isFindUser) {
				if(BankArray.adminId.equals(BankArray.inputId) && BankArray.adminPw.equals(BankArray.inputPw)) {
					System.out.println("관리자님 어서오세요.");
					BankArray.loginUserStatus = BankArray.STATE_ADMIN_LOGIN;
				} else {
					System.out.println("없는 아이디입니다. 다시 입력해주세요.");
				}
			}
				if(BankArray.inputId.equals("EXIT")) {
					BankArray.loginUserStatus = BankArray.STATE_EXIT;
					System.out.println("프로그램을 종료합니다. 이용해주셔서 감사합니다.");
				}
				switch(BankArray.loginUserStatus) {
				case BankArray.STATE_ADMIN_LOGIN:
					System.out.println("관리자 관련 작업메뉴");
					boolean isAdmMenu = true;
					while(isAdmMenu) {
						System.out.println("1. 계정추가 | 2. 계정삭제 | 3. id변경 | 4. 모든 사용자 출력 | 5. 종료");
						switch(scanner.nextLine()) {
						case "1":
							System.out.print("추가할 아이디 입력> ");
							inputId = scanner.nextLine();
							System.out.print("추가할 암호 입력> ");
							inputPw = scanner.nextLine();
							id[BankArray.totalUserCount] = inputId;
							pw[BankArray.totalUserCount] = inputPw;
							account[BankArray.totalUserCount] = 100;
							System.out.println(id[BankArray.totalUserCount] + "계정 생성");
							BankArray.totalUserCount++;
							break;
						case "2":
							System.out.print("삭제할 아이디 입력> ");
							inputId = scanner.nextLine();
							int findIndex = BankArray.totalUserCount;
							for(int i=0; i<BankArray.totalUserCount; i++) {
								if(id[i].equals(inputId)) {
									findIndex = i;
								}
							}
							for(int i=findIndex; i<BankArray.totalUserCount; i++) {
								id[i] = id[i + 1];
								pw[i] = pw[i + 1];
								account[i] = account[i + 1];
							}
							BankArray.totalUserCount--;
							break;
						case "3":
							System.out.print("변경할 아이디 입력> ");
							inputId = scanner.nextLine();
							for(int i=0; i<BankArray.totalUserCount; i++) {
								if(id[i].equals(inputId)) {
									System.out.print("변경할 아이디> ");
									id[i]=scanner.nextLine();
									System.out.print("변경할 암호> ");
									pw[i] = scanner.nextLine();
									System.out.print("변경할 account> ");
									account[i] = Double.parseDouble(scanner.nextLine());									
								}
							}
							break;
						case "4":
							System.out.println("출력 시작");
							for(int i=0; i<BankArray.totalUserCount; i++) {
								System.out.print(i + "번째 아이디> " + id[i]);
								System.out.print(" pw> " + pw[i]);
								System.out.println(" account> " + account[i]);
							}
							System.out.println("모두 출력");
							break;
						case "5":
							System.out.println("관리자 메뉴 종료");
							BankArray.loginUserStatus = BankArray.STATE_LOGOUT;
							isAdmMenu = false;
							break;
						}
					}
					break;
				case BankArray.STATE_USER_LOGIN:
					System.out.println("사용자 관련 작업메뉴");
					boolean isUseMenu = true;
					while(isUseMenu) {
						System.out.println("1. 입금 | 2. 출금 | 3. 잔액 조회 | 4. 종료 입력");
						switch(scanner.nextLine()) {
						case "1":
							System.out.println("입금액 입력> ");
							InputAccount = Double.parseDouble(scanner.nextLine());
							account[BankArray.loginUserIndex] += InputAccount;
							System.out.println(id[BankArray.loginUserIndex] + "님 잔액:" + account[BankArray.loginUserIndex]);
							break;
						case "2":
							System.out.println("출금액 입력> ");
							InputAccount = Double.parseDouble(scanner.nextLine());
							account[BankArray.loginUserIndex] -= InputAccount;
							System.out.println(id[BankArray.loginUserIndex] + "님 잔액:" + account[BankArray.loginUserIndex]);
							break;
						case "3":
							System.out.println("잔액 조회>>");
							System.out.println(id[BankArray.loginUserIndex] + "님 잔액:" + account[BankArray.loginUserIndex]);
							break;
						case "4":
							System.out.println("사용자 메뉴 종료");
							BankArray.loginUserStatus = BankArray.STATE_LOGOUT;
							isUseMenu = false;
							break;
						}
					}
					break;
				case BankArray.STATE_LOGOUT:
					System.out.println("로그아웃하였습니다.");
					break;
				case BankArray.STATE_EXIT:
					System.out.println("프로그램을 종료합니다.");
					break;
				default:
					System.out.println("알 수 없는 문제가 발생한 상태입니다.");
				}
			}
			System.out.println("프로그램 종료");
	}

2. 프로그램 구현

- 자바로 간단한 프로그램 구현하였음.
- 챗gpt 예제를 참고하여 학습.
- 반복적으로 쳐보기

(1) 로또 프로그램 구현

import java.util.Arrays;
import java.util.Random;
public static void main(String[] args) {
// generate: 데이터를 생성하거나 만드는데 사용하는 언어
int[] lottoNumbers = generateLottoNumbers();
// 생성된 로또번호 출력
System.out.print("로또 번호: ");
// int타입의 number를 참조하여 lottoNumbers 요소를 순회하여 반복가능한 자료구조.
for(int number : lottoNumbers) {
	System.out.print(number + " ");
	}
}
public static int[] generateLottoNumbers() {
	int[] numbers = new int[45];
    // 1~45까지의 숫자를 배열에 저장
    for(int i=0; i<45; i++) {
    	numbers[i] = i + 1; // 로또번호는 1부터
    }
    // 배열을 무작위로 섞음.
    shuffleArray(numbers);
    // 섞인 숫자 중 앞에서 6개를 선택하여 로또번호 반환
    // Arrays.copyOfRange: 배열의 일부분 요소를 복사하여 새로운 배열 생성함.
    int[] lottoNumbers = Arrays.copyOfRange(numbers, 0, 6);
    // 로또번호를 오름차순 정렬
    Arrays.sort(lottoNumbers);
   	return lottoNumbers;
}
public static void shuffleArray(int[] array) {
	int index, temp;
    Random random = new Random();
    for(int i=0; i<array.length; i++) {
    	index = random.nextInt(i+1);
        temp = array[index];
        array[index] = array[i];
        array[i] = temp;
       }
   }
}

(2) 사용자로부터 이름을 출력받는 프로그램

import java.util.Scanner;
public class Practice {
	public static void main(String[] args) {
    	Scanner scanner = new Scanner(System.in);
        System.out.print("이름을 입력해주세요> ");
        String name = scanner.nextLine();
        System.out.println("안녕하세요, " + name + "님! 환영합니다.");
        }
  }

(3) 사용자로부터 두 수를 입력받고 합을 구하는 프로그램

import java.util.Scanner;
public class Practice {
	public static void main(String[] args) {
    	Scanner scanner = new Scanner(System.in);
        //사용자로부터 두 수를 입력받고 합을 출력
        System.out.print("첫번째 숫자를 입력하세요> ");
        int num1 = Integer.parseInt(scanner.nextLine());
        System.out.print("두번째 숫자를 입력하세요> ");
        int num2 = Integer.parseInt(scanner.nextLine());
        int sum = num1 + num2;
        System.out.println("두 수의 합은 " + sum + "입니다.");
        }
   }

(4) 간단한 결제 프로그램 구현

import java.util.Scanner;
public class Practice {
	public static void main(String[] args) {
    	Scanner scanner = new Scanner(System.in);
        // 상품 가격 입력
        System.out.print("상품 가격을 입력해주세요> ");
        double productPrice = Double.parseDouble(scanner.nextLine());
        // 지불한 금액 입력
        System.out.print("지불한 금액을 입력해주세요> ");
        double paymentPrice = Double.parseDouble(scanner.nextLine());
        // 거스름돈 계산
        double change = paymentPrice - productPrice;
        if(change >= 0) {
        	System.out.println("거스름돈: " + change + "원 입니다.");
        } else {
        	System.out.println("지불 금액이 부족합니다. " + (-change) + "원을 더 지불해주세요");
        }
   }
}

(5) 난이도(上) 로그인 창 구현

- 반복해서 쳐보되 난이도가 높다는 것을 인지할 것.
import java.awt.GridLayout;
import java.awt.event.*;
import javax.swing.*;
public class Practice {
	public static void main(String[] args) {
    	// 로그인 창 생성
        JFrame frame = new JFrame("로그인");
        // Java Swing 프레임을 닫을 때 어떻게 동작해야 하는지 설정하는 부분.
        // setDefaultCloseOperation은 JFrame의 종료동작을 설정하는데 사용함.
        frame.setSize(300,150);
        // GridLayout: 그리드 형식의 컴포넌트 배치하는 레이아웃 매니저 중 하나.
        // new GridLayout(3,2)는 3개의 행과 2개의 열을 가진 그리드가 생성
        frame.setLayout(new GridLayout(3,2));
        // 라벨 및 입력 필드 추가
        JLabel usernameLabel = new JLabel("사용자 이름:");
        JTextField usernameField = new JTextField();
        JLabel passwordLabel = new JLabel("비밀번호:");
        JPasswordField passwordField = new JPasswordField();
        // 버튼 추가
        JButton loginButton = new Button("로그인");
        // 로그인 버튼 클릭시 이벤트처리
        // addActionListener은 Java Swing의 AWT(추상 윈도우 툴킷) 라이브러리에서 사용되는 이벤트
        // 사용자 인터페이스 컴포넌트에서 발생한 이벤트 처리
        loginButton.addActionListener(new ActionListener() {
        	@Override // 메소드 오버라이딩: 메소드 재정의
            // 이벤트가 발생했을 때 호출함.
            // getText()는 텍스트를 가져올때 사용함
            public void actionPerformed(ActionEvent e) {
            	String username = usernameField.getText();
                char[] passwordChars = passwordField.getPassword();
                String password = new String(passwordChars);
                if(username.equals("admin") && password.equals("password")) {
                	// JOptionPane: 다이얼로그 상자가 표시될 컴포넌트.
                    JOptionPane.showMessageDialog(frame,"로그인 성공");
               } else {
               	JOptionPane.showMessageDialog(frame, "로그인 실패. 다시 시도해보세요");
               }
               // 비밀번호 필드 지우기
               password.setText("");
           }
      });
      // 컴포넌트: UI를 가리키는 요소(버튼, 텍스트필드, 체크박스, 레이블, 콤보박스 등)
      frame.add(usernameLabel);
      frame.add(usernameField);
      frame.add(passwordLabel);
      frame.add(passwordField);
      frame.add(new JLabel());
      frame.add(loginButton);
      // 프레임을 화면에 표시
      frame.setVisible(true);
      }
 }

(6) 출석부 프로그램 구현

- HashMap을 활용하여 풀이

1) HashMap

  • 컬렉션 프레임워크에서 제공되는 데이터 구조
  • 키와 값을 쌍으로 데이터를 저장함.

(1) 키

  • 중복x, 검색과 값의 연결을 가능하게 함.

(2) 값(Value)

  • 실제 정보

2) HashMap 사용법

  1. 데이터 추가 및 검색
  • put(key, value) 메소드를 사용하여 데이터 추가.
  • get(key) 메소드를 사용하여 키에 대한 값 검색
  1. 데이터 삭제
  • remove(key) 메소드를 사용하여 특정 키와 데이터 삭제
  1. 순회
  • HashMap의 모든 키-값 쌍을 순회하려면 keySet() 메소드의 키의 집합을 얻고 반복문 사용하여 키에 대한 값 찾기
  1. 크기 확인
  • size() 메소드를 사용하여 HashMap 크기 확인
  1. Null 허용
  • HashMap은 하나의 null키와 여러 개의 null값 처리 지원
  1. 동기화
  • 멀티스레드 환경에 사용할때 동기화 처리 필요
  • ConcurrentHashMap 등 동기화된 맵 사용 가능
  1. 성능
  • HashMap은 해시테이블 기반으로 함.
import java.util.Scanner;
import java.util.HashMap;
public class Practice {
	public static void main(String[] args) {
    	Scanner scanner = new Scanner(System.in);
        HashMap<String,Boolean> attendanceRecord = new HashMap<>();
        while(true) {
        	System.out.println(1. 출석 기록);
           	System.out.println(2. 출석 확인);
            System.out.println(3. 프로그램 종료);
            System.out.print("선택> ");
           	int choice = Integer.parseInt(scanner.nextLine());
            switch(choice) {
            case 1:
            	System.out.print("학생 이름을 입력해주세요> ");
                String studentName = scanner.nextLine();
                // 데이터 추가
                attendanceRecord.put(studentName, true);
                System.out.println(studentName + "님이 출석되었습니다");
                break;
            case 2:
            	System.out.print("학생 이름을 입력해주세요> ");
                String studentName = scanner.nextLine();
                Boolean isPresent = attendanceRecorde.get(studentName);
                if(isPresent != null && isPresent) {
                	System.out.println(studentName + "님이 출석되었습니다.");
               } else {
               	System.out.println(studentName + "님이 결석되었습니다.");
               }
               break;
            case 3:
            	System.out.println("프로그램을 종료합니다");
                break;
            default:
            	System.out.println("잘못된 접근입니다.");
                break;
             }
        }
    }

(7) 간단한 게시판 구현

import java.util.Scanner;

public class Practice {
	public static final int MAX_POSTS = 100;
	public String[] posts = new String[MAX_POSTS];
	public int PostCount = 0;
	public Scanner scanner = new Scanner(System.in);
	
	public void run() {
		while(true) {
			System.out.println("1. 글쓰기");
			System.out.println("2. 글 목록 보기");
			System.out.println("3. 프로그램 종료");
			System.out.print("선택> ");
			
			int choice = Integer.parseInt(scanner.nextLine());
			switch(choice) {
			case 1:
				writePosts();
				break;
			case 2:
				listPosts();
				break;
			case 3:
				scanner.close();
				System.out.println("프로그램을 종료합니다.");
				break;
			default:
				System.out.println("올바른 메뉴를 선택해주세요");
			}
		}
	}
	public void writePosts() {
		if(PostCount < MAX_POSTS) {
			System.out.print("글을 입력해주세요> ");
			String content = scanner.nextLine();
			posts[PostCount] = content;
			PostCount++;
			System.out.println("글이 작성되었습니다.");
			System.out.println();
		} else {
			System.out.println("더 이상 글을 작성할 수 없습니다");
		}
	}
	public void listPosts() {
		if(PostCount == 0) {
			System.out.println("게시물이 없습니다.");
			return;
		}
		System.out.println("----------글 목록----------");
		for(int i=0; i<PostCount; i++) {
			System.out.println((i + 1) + ". " + posts[i]);
		}
		System.out.println("--------------------------");
	}	
	public static void main(String[] args) {
		Practice board = new Practice();
		board.run();
		}
	}

(8) 369 해답지 추가 설명

for(int i=0; i<1000; i++) {
	int oriNum = 2916;
    String str = "";
    int num = oriNum;
    while(num!=0) {
    	// num에 10을 나눈 나머지 값에 3을 나눠 나머지가 0이고 
        // num에 10을 나눈 나머지가 0이 아닐때 true
    	if(num%10%3 == 0 && num%10 !=0) {
        	 str = str + "짝";
       }
       num = num/10;
    }
    if(str.equals("")) {
    	System.out.println(oriNum);
    } else {
    	System.out.println(str + "("+oriNum+")");
    }
 }
//		int orinum = 2916;
//		String str =  "";
//		
//		int num = orinum;
//		
//		while(num!=0) {
//			if(num%10%3==0 && num%10 !=0) {
//				str = str + "짝";
//			}
//			num = num/10;
//		}
//		if((num % 10) % 3 == 0 && num %10 != 0) {
//			str = str + "짝";
//		}
//		num = num / 10; // 291
//		
//		if((num % 10) % 3 == 0 && num %10 != 0) {
//			str = str + "짝";
//		}
//		num = num / 10; // 29
//		
//		if((num % 10) % 3 == 0 && num %10 != 0) {
//			str = str + "짝";
//		}
//		num = num / 10; // 2
//		
//		if((num % 10) % 3 == 0 && num %10 != 0) {
//			str = str + "짝";
//		}
//		num = num / 10; // 0
//		
//		if(str.equals("")) {
//			System.out.println(orinum);
//		} else {		
//			System.out.println(str + "("+orinum+")");
//		}
profile
IT 개발자가 되기 위한 기록

0개의 댓글