나의 수업일지

인천 일보 아카데미 9일차 static을_알아보자

GUPING 2023. 3. 6. 21:04
  • static을_알아보자
    public class Board { > 필드는 각각 개체가 고유하게 가진 데이터
    > 스태틱을 알아보자 = 스태틱은 공유
    static int number = 0; > class로 만들어진 모든 객체에서 데이터를 공유하는 필드
    private int bno;
    private String title;
    private String writer;
    private int cnt;
    private String postDate;

    public Board() {
	number++;
    }
    public Board(int bon , String title , String writer , int cnt , String pstDate) {
        this.bno = bno;
        this.cnt = cnt;
        this.postDate = postDate;
        this.title = title;
        this.writer = writer;
    }

    ====================================================================
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        > 스태틱의 이해를 돕는 예시문
        Board b1 = new Board(); 
        Board b2 = new Board(); 
        < 이렇게 객체를 2개 만든 경우 객체가 만들어지며 기본 생성자를 실행하기에
        < number를 출력해보면 2가 찍히는걸 확인 할 수 있습니다
        System.out.println(b2.getNumber());
        b1.setBno(9);
        System.out.println(b2.getBno());

        b1.number = 5; < 이렇게 먼저 대입받고 출력하면 5가 출력됩니다
        System.out.println(b2.number);
        b2.number = 10; < 하지만 여기서 10을 넣고 출력하면 number은 10으로 바뀝니다 
        System.out.println(b1.number);

 

  • static의_활용
    private static int number = 0;
    private final static DateTimeFormatter DTF = DateTimeFormatter.ofPattern("yyyy년MM월dd일");
            > 고정된 값을 표기할때 final을 붙여준다
    private int bno;
    private String title;
    private String writer;
    private int cnt;
    private String postDate;

    public Board() {> 객체를 생성하는 생성자 보드에 스태틱 넘버를 넣어 생성자 보드로 객체를 만들면 1씩증가하게함
        this.bno = ++number;
        this.cnt = 0;
        this.postDate = DTF.format(LocalDateTime.now());

        > 객체가 생성될때 자동으로값이 들어가는 개체들을 굳이 적지 않고 자동으로 들어가게 함 

    }

    public Board(int bon , String title , String writer , int cnt , String pstDate) {
        this.bno = bno;
        this.cnt = cnt;
        this.postDate = postDate;
        this.title = title;
        this.writer = writer;
    }
    public void setBno(int bno) {
        this.bno = bno;
    }

    public int getBno() {
        return this.bno;
    }
    ======================================================================================
        Board b1 = new Board();
        Board b2 = new Board();
        b1.setBno();
        System.out.println(b2.getBno()); > 둘다 똑같이 2가 출력되는것을 확인 할 수 있다
            System.out.println(b1.getBno()); > 스태틱은 객체를 따로 만들어도 같은 클래스라면 공유하기 때문이다

 

  • 응용_만들어보기
public class Board {> 필드는 각각 개체가 고유하게 가진 데이터
    > 스태틱을 알아보자 = 스태틱은 공유
    private static int number = 0;
    private final static DateTimeFormatter DTF = DateTimeFormatter.ofPattern("yyyy년MM월dd일");
            > 변경 불가능한 값을 표기할때 final을 앞에 붙여준다 
    private int bno;
    private String pw;
    private String title;
    private String writer;
    private int cnt;
    private String postDate;

    public Board() {> 객체를 생성하는 생성자 보드에 스태틱 넘버를 넣어 생성자 보드로 객체를 만들면 1씩증가하게함
        this.bno = ++number;
        this.cnt = 0;
        this.postDate = DTF.format(LocalDateTime.now());

        > 객체가 생성될때 자동으로값이 들어가는 개체들을 굳이 적지 않고 자동으로 들어가게 함 

    }

    public Board(String title , String writer , String pw) {
        this.bno = ++number;
        this.cnt = 0;
        this.postDate = DTF.format(LocalDateTime.now());
        this.title = title;
        this.writer = writer;
        this.pw = pw;
    }

    public int getBno() {
        return this.bno;
    }
    public void setPw(String pw) {
        this.pw = pw;
    }
    public String getPw() {
        return this.pw;
    }

    public String getTitle() {
        return this.title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getWriter() {
        return this.writer;
    }

    public void setWriter(String writer) {
        this.writer = writer;
    }

    public void increaseCnt() {
        this.cnt++;
    }

    public void print() {
        System.out.printf("%d\t%s\t\t%s\t%d\t%s\n",bno,title,writer,cnt,postDate);
    }
}

=======================================================================================

	Scanner sc = new Scanner(System.in);
	List<Board> list = new ArrayList<>();
	>사용자가 작성할수 있게만드는 scanner
    >배열로 만들수도 있지만 좀 더 편하게 저장하고 꺼내와 사용할 수 있는 저장소 ArrayList를 만든모습
        
        while (true) { < 메뉴를 반복하며 보여주기 위한 반복문 while
            System.out.println("==============게시판==============");
            System.out.println("1.게시물등록 2.리스트 3.읽기 4.수정 5.삭제 0.종료");
            System.out.println("메뉴선택 >");
            int menu = sc.nextInt();sc.nextLine();
            < 사용자의 입력 정보를 menu에 저장
            < 아래에 띄어쓰기를 사용하는 실행문이 있기 떄문에 nextLine 을 사용
            < 사용자가 입력할때 엔터까지 값으로 지정하기 떄문에 Int뿐만 아니라 Line까지 사용하여
            < 미리 엔터의 값을 빼준모습이다
            
            if (menu == 1) {
                System.out.println("제목");
                String title = sc.nextLine();
                 < nextLine은 엔터뿐만 아니라 띄어쓰기 까지 저장가능하기에 
                 < 책제목에 띄어쓰기가 있을때를 대비하여 사용함
                System.out.println("작성자");
                String writer = sc.next();
                System.out.println("비밀번호 입력 >");
                String pw = sc.next();
                Board board = new Board(title, writer, pw);
                list.add(board);
                System.out.println(title + "이(가) 등록되었습니다");

            } else if (menu == 2) {
                System.out.println("글번호\t제목\t\t작성자\t조회수\t게시일");
                System.out.println("----------------------------------------------------");
                for (Board b : list) { < list에 저장된 정보를 b에 대입하며 프린트하는 향상된 for문
                    b.print();
                }
            } else if (menu == 3) {
                System.out.println("읽을 글 번호 >");
                int bno = sc.nextInt();
                System.out.println("글번호\t제목\t\t작성자\t조회수\t게시일");
                System.out.println("----------------------------------------------------");
                boolean find = false;
                for (Board b : list) { < list에 저장된 정보를 가져오는 향상된 for문
                    if (bno == b.getBno()) { < 조건문 if를 사용하여 입력받은 정보와 같다면 실행
                        b.increaseCnt();
                        b.print();
                        find = true;
                        break;
                    }
                }
                if (!find) { < 조건문을 사용하여 find가 계속 false일 경우 조회 실패를 프린트함
                    System.out.println("조회할 수 없는 글번호입니다");
                }

            } else if (menu == 4) {
                boolean find = false;
                System.out.println("수정할 글 번호 >");
                int updateBno = sc.nextInt();sc.nextLine();
                > 글을 입력하면 버퍼라는곳에 저장하는데 입력할때 사용하는 엔터까지 값으로 친다
                > nextIne는 숫자만 가져가는데 엔터값이 남게되고 뒤에 line이 없다면 아래있는 line으로 넘어가게된다
                > 그렇기 때문에 nextInt와 line을 붙여 엔터값을 라인으로 빼는것이다
                
                System.out.println("비밀번호 >");
                String updatePw = sc.next();sc.nextLine();
                for (Board up : list) {
                    if (updateBno == up.getBno()) {
                        if (updatePw.equals(up.getPw())) {
                            System.out.println("수정할 제목 >");
                            String updateTitle = sc.nextLine();
                            System.out.println("수정할 작성자 >");
                            String updateWriter = sc.next();
                            up.setTitle(updateTitle);
                            up.setWriter(updateWriter);
                            System.out.println("글 수정 완료!");
                            find = true;
                            break;
                        }
                    }
                }
                if (!find) {
                    System.out.println("글 번호 또는 비밀번호를 확인해주세요");
                }

            } else if (menu == 5) {
                System.out.println("삭제할 글번호 >");
                int deleteBno = sc.nextInt();
                System.out.println("비밀번호 >");
                String deletePw = sc.next();
                for(Board b : list) {
                    if (deleteBno == b.getBno() && deletePw.equals(b.getPw())){
                        System.out.println(b.getTitle()+" 이(가) 삭제되었습니다");
                        list.remove(b);
                        break;
                    }
                }
            } else if (menu == 0) {
                break;
            } else {
                System.out.println("다시입력");
            }
            System.out.println();
        }
        System.out.println("프로그램종료");
    }

}

 

  • 응용_성적표_만들어보기
public class Student {
    private static int num = 100; 
    < 학범으로 사용할 필드변수 static이기 떄문에 객체를 몇개를 만들어도 공유한다
    < 그렇기 때문에 중복된 학범이 나올 수 없고 코드를 짜기 매우 편해진다

    private String sno;
    private String name;
    private int kor;
    private int eng;
    private int mat;
    private int total;
    private double avg;
    private char grade;
    private String pw;

    public Student() {
        this.sno = "S" + num++; < 기본 생성자를 이용하여 객체가 자동으로 정보를 넣어주고 num을 1증가시킨다
    }

    public String getSno() {
        return sno;
    }

    public void setSno(String sno) {
        this.sno = sno;
    }

    public String getPw() {
        return pw;
    }

    public void setPw(String pw) {
        this.pw = pw;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getKor() {
        return kor;
    }

    public void setKor(int kor) {
        this.kor = kor;
    }

    public int getEng() {
        return eng;
    }

    public void setEng(int eng) {
        this.eng = eng;
    }

    public int getMat() {
        return mat;
    }

    public void setMat(int mat) {
        this.mat = mat;
    }

    public int getTotal() {
        return total;
    }

    public void setTotal() {
        this.total = kor + eng + mat; 
        < total을 저장할때 사용자에게 받아 저장하는게 아닌 계산을하여 저장해야 하기 떄문에
        < 사용자가 각 과목의 점수를 넣을 필드변수를 합하여 필드 변수 total에 대입하게 하였음
    }

    public double getAvg() {
        return avg;
    }

    public void setAvg() {
        this.avg = this.total / (double) 3;
        < 이또한 마찬가지로 사용자가 계산을 쉽게하기 위한 프로그램이기 때문에
        < 메소드에 계산하는 식을 넣어 저장할때 계산값을 넣게 하였음
    }

    public char getGrade() {
        return grade;
    }

    public void setGrade() { < 학점을 저장하는 메소드 필드에 있는 avg의 점수에 따라 조건에 맞는 학점을 저장하게 하였음
        char grade = ' ';
        if (this.avg >= 90) {
            grade = 'A';
        }else if(this.avg >=80){
            grade = 'B';
        }else if(this.avg >=70){
            grade = 'C';
        }else if(this.avg >=60){
            grade = 'D';
        }else {
            grade = 'F';
        }
        this.grade = grade;
    }
    public void print() {
        System.out.printf("%s\t%s\t%d\t%d\t%d\t%d\t%.2f\t%c\n",sno ,name , kor, eng, mat , total , avg ,grade);
    }
}

===================================================================================================
> 여기서부터는 읽어보며 이해가 안되는 부분이 있다면 블로그 글을 다시 한번 읽어보자 !!

public class Student_Main {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc = new Scanner(System.in);
		List<Student> list = new ArrayList<>();

		while (true) {
			System.out.println("===============성적표 리스트==============");
			System.out.println("1.학생등록 2. 리스트 3.검색 4.수정 5.삭제 0.종료");
			System.out.print("메뉴선택 >");
			int menu = sc.nextInt();
            System.out.print();

			if (menu == 1) {
				Student student = new Student();
				System.out.print("이름 >");
				student.setName(sc.next());
				System.out.print("비밀 번호 >");
				student.setPw(sc.next());
				System.out.print("국어 점수 >");
				student.setKor(sc.nextInt());
				System.out.print("영어 점수 >");
				student.setEng(sc.nextInt());
				System.out.print("수학 점수 >");
				student.setMat(sc.nextInt());
				student.setTotal();
				student.setAvg();
				student.setGrade();
				list.add(student);
				System.out.println(student.getName() + "님 등록되었습니다\n");
			} else if (menu == 2) {
				System.out.println("학번\t이름\t국어\t영어\t수학\t총점\t평균\t학점");
				System.out.println("-----------------------------------------------------------");
				for (Student s : list) {
					s.print();
				}
			} else if (menu == 3) {
				System.out.print("학번 입력 >");
				String src = sc.next();
				System.out.print("비밀번호 입력 >\n");
				String pw = sc.next();
				boolean find = false;
				for (Student s : list) {
					if (s.getSno().equals(src)) {
						if (s.getPw().equals(pw)) {
							System.out.println("학번\t이름\t국어\t영어\t수학\t총점\t평균\t학점");
							System.out.println("-----------------------------------------------------------");
							s.print();
							find = true;
						}
					}
				}
				if(!find) {
					System.out.println("입력 정보를 확인해주세요\n");
				}

			} else if (menu == 4) {
            
             > 입력 정보가 잘못되었을때 수정하기 위한 공간을 만듬
             > 점수를 수정하면 total,avg.grade까지 모두 새로 저장해 주어야함!
				System.out.print("학번 입력 >");
				String src = sc.next();
				System.out.print("비밀 번호입력 >");
				String pw = sc.next();
				boolean find = false;
				for (Student s : list) {
					if (s.getSno().equals(src)) {
						if (s.getPw().equals(pw)) {
							System.out.print("국어 점수 >");
							s.setKor(sc.nextInt());
							System.out.print("영어 점수 >");
							s.setEng(sc.nextInt());
							System.out.print("수학 점수 >");
							s.setMat(sc.nextInt());
							s.setTotal();
							s.setAvg();
							s.setGrade();
							System.out.println(s.getName()+"님 정보 수정 완료!\n");
							find = true;
						}
					}
				}
				if(!find) {
					System.out.println("입력 정보를 확인해주세요\n");
				}

			} else if (menu == 5) {
				System.out.print("학번 입력 >");
				String src = sc.next();
				System.out.print("비밀 번호입력 >");
				String pw = sc.next();
				boolean find = false;
				for (Student s : list) {
					if (s.getSno().equals(src)) {
						if (s.getPw().equals(pw)) {
							System.out.println(s.getName()+"님 삭제 완료!\n");
							list.remove(s);
							find = true;
							break;
						}
					}
				}
				if(!find) {
					System.out.println("입력 정보를 확인해주세요\n");
				}

			} else if (menu == 0) {
				break;
			} else {
				System.out.println("없는 메뉴입니다\n");
			}
		}
		System.out.println("없는 메뉴입니다\n");
	}

}

 

  • 스택_힙
int는 값이 스택에 저장된다 하지만 String이나 배열은 값은 힙에 저장되고 저장된 주소가 스택에 저장된다
그렇기에 int는 == 으로 같으면을 사용 힐 수 있지만 
String이나 배열의 경우 스택에 저장된 값이 주소값이기 때문에
힙안에있는 메모리를 비교할 수 있는 equals을 사용하여 비교한다
    
    ==는 스택 값을 비교
    equals는 힙메모리를 비교

 

  • 만들어보기_응용
>> 숙제를 대비하여 선생님과 함께 만들어본 작업물입니다 <<
>> 읽어보며 숙제를 진행합시다....<<

public class Bank {
	private static int number = 1000;
	private final static DateTimeFormatter DTF = DateTimeFormatter.ofPattern("yy/MM//dd hh:mm:ss");

	private String account;
	private String name;
	private long balance;
	private List<String> breakdown = new ArrayList<>(); // 내역을 집어 넣을 참조형 변수 기본변수가 null이기 떄문에 어레이를 꼭 해줘야함

	public void deposit(int money) {
		this.balance += money;
		String date = DTF.format(LocalDateTime.now());
		String str = "입금\t"+money+"\t잔액:"+balance+"\t"+date;
		breakdown.add(str);
	}
	
	public boolean withdraw(int money) {
		boolean result = false;
		if(this.balance >= money) {
			this.balance -= money;
			String date = DTF.format(LocalDateTime.now());
			String str = "출금\t"+money+"\t잔액:"+balance+"\t"+date;
			breakdown.add(str);
			result = true;
		}
		return result;
	}
	
	
	public String getAccount() {
		return account;
	}

	public void setAccount(String account) {
		this.account = number++ + "-" + account;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public long getBalance() {
		return balance;
	}

	public void setBalance(long balance) {
		this.balance = balance;
		String date = DTF.format(LocalDateTime.now());
		String str = "입금\t"+balance+"\t잔액:"+balance+"\t"+date;
		breakdown.add(str);
	}

	public List<String> getBreakdown() {
		return breakdown;
	}

	public void setBreakdown(List<String> breakdown) {
		this.breakdown = breakdown;
	}
	
	public void breakdownPrint() {
		System.out.println("구분\t금액\t거래후잔액\t\t거래날짜");
		System.out.println("----------------------------------------------");
		for(String s : breakdown) {
			System.out.println(s);
		}
	}


	public void print() {
		System.out.printf("%s\t%s\t%d\n", account, name, balance);
	}

}

===========================================================================================

package day9;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Bank_Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		Scanner sc = new Scanner(System.in);
		List<Bank> list = new ArrayList<>();

		while (true) {
			System.out.println("======================은행======================");
			System.out.println("1.계좌 생성 2.리스트 3.입금 4.출금 5.계좌이체 6.조회 0.종료");
			System.out.print("메뉴 선택 >");
			int menu = sc.nextInt();

			if (menu == 1) {
				Bank bank = new Bank();
				System.out.print("계좌 번호 >");
				bank.setAccount(sc.next());
				System.out.print("예금주 > ");
				bank.setName(sc.next());
				System.out.print("초기입금 금액 >");
				bank.setBalance(sc.nextLong());
				list.add(bank);
				System.out.println("계좌 생성 완료!");
			} else if (menu == 2) {
				System.out.println("계좌번호\t\t예금주\t잔액");
				System.out.println("--------------------------------------");
				for (Bank b : list) {
					b.print();
					System.out.println();
				}
			} else if (menu == 3) {
				System.out.println("입금 계좌 >");
				String account = sc.next();
				boolean find = false;
				for (Bank b : list) {
					if (account.equals(b.getAccount())) {
						System.out.println("입금 금액 >");
						int money = sc.nextInt();
						b.deposit(money);
						System.out.println("입금 완료!");
						find = true;
						break;
					}
				}
				if (!find) {
					System.out.println("계좌번호를 확인해주세요");
				}
			} else if (menu == 4) {
				System.out.println("출금 계좌");
				String account = sc.next();
				boolean find = false;
				for (Bank b : list) {
					if (account.equals(b.getAccount())) {
						System.out.println("출금 금액>");
						int money = sc.nextInt();
						if (b.withdraw(money)) {
							System.out.println("출금 완료");
							find = true;
							break;
						} else {
							System.out.println("잔액이 부족합니다.");
						}
					}
				}
				if (!find) {
					System.out.println("계좌 번호를 확인해주세요");
				}

			} else if (menu == 5) {
				System.out.println("출금 계좌 >");
				String account = sc.next();
				System.out.println("이체 계좌 >");
				String account1 = sc.next();

				Bank w = null;
				Bank d = null;

				for (Bank b : list) {
					if (account.equals(b.getAccount())) {
						w = b;
					}
					if (account1.equals(b.getAccount())) {
						d = b;
					}
				}
				if (w == null) {
					System.out.println("출금계좌 없음");
				} else if (d == null) {
					System.out.println("입금계좌 없음");
				} else {
					System.out.println("계좌이체 금액 >");
					int money = sc.nextInt();
					if (w.withdraw(money)) {
						d.deposit(money);
						System.out.println("계좌 이체 완료");
					} else {
						System.out.println("잔액부족");
					}
				}
			} else if (menu == 6) {
				System.out.println("조회할 계좌 번호 >");
				String searchAccount = sc.next();
				boolean find = false;
				for (Bank b : list) {
					if (searchAccount.equals(b.getAccount())) {
						b.breakdownPrint();
						find = true;
						break;
					}
				}
				if (!find) {
					System.out.println("계좌번호를 확인해주세요");
				}

			} else if (menu == 0) {
				System.out.println("프로그램을 종료합니다");
				break;
			} else {
				System.out.println("없는 메뉴 입니다.");
			}
		}

	}
}