상세 컨텐츠

본문 제목

2023.01.09

Java

by 연을 2023. 1. 9. 17:28

본문

728x90

<Order Class>      Order class에서 Menu class를 가져오기 위한 방법 

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

public class Order {
	ArrayList<String> alName;
	ArrayList<Integer> alCount;
	ArrayList<Integer> alSum;
	Menu m;//Menu class를 가져오기 위해서 선언한다.
	
	Scanner s1;
	
	public Order(Menu m) {
		this.alName = new ArrayList<String>();
		this.alCount = new ArrayList<Integer>();
		this.alSum = new ArrayList<Integer>();
		this.m = m;
		s1= new Scanner(System.in);
	}
	void build() {
		this.m.display();//Menu class를 가져오기
		System.out.println("원하는 메뉴번호, [나가기 -1]");
		int m_num=this.m.s1.nextInt();//메뉴class에서 가져온다.
		while(m_num!=-1) {
			System.out.println("수량?, [나가기 -1]");
			int qty=m.s1.nextInt();
			String name = this.m.alMenu.get(m_num);
			int price = this.m.alPrice.get(m_num);
			
			this.append(name, qty, price);//주문내역 저장
			
			this.m.display();
			System.out.println("원하는 메뉴번호, [나가기 -1]");
			m_num=this.m.s1.nextInt();
		}
	}
	void remove() {
		//주문내역출력
		//삭제할 주문번호 입력
		//while(주문번호!=-1){
		//		삭제(delete());
		//		주문내역출력
		//		삭제할 주문번호 입력
		//}
		this.display();
		System.out.println("원하는 주문번호, 나가기 -1");
		int m_num=this.s1.nextInt();
		while(m_num!=-1) {
			this.delete(m_num);
			this.display();
			System.out.println("삭제할 주문번호, 나가기 -1");
			m_num=this.s1.nextInt();
		}
	}
	
	void append(String name, int qty, int net) {//메뉴, 수량, 단가 추가
		this.alName.add(name); 
		this.alCount.add(qty);
		this.alSum.add(qty*net);
	}
	
	void display() {
		for(int i=0; i<alName.size();i++) {
			System.out.println("번호 "+i+" 메뉴 : "+alName.get(i)+" 수량 : "+alCount.get(i)+" 총액 : "+alSum.get(i));
		}
	}
	void delete(int order_num) {
		this.alName.remove(order_num);
		this.alCount.remove(order_num);
		this.alSum.remove(order_num);
	}

}

menu class에서 order class로 넘어오는 설명 그림

<Main>

import java.util.ArrayList;
		import java.util.Scanner;
public class Cafe {

	public static void main(String[] args) {
			Scanner s = new Scanner(System.in);
			Scanner s1 = new Scanner(System.in);

			Menu menu = new Menu();
			
			String job="";
			String mjob="";

			int Price;
			int MenuNum=0;
			int pi=0;
			int total=0;
			do {
				System.out.println("실행하실 관리를 선택하세요:[m:메뉴관리] [o:주문관리] [s:매출관리] [Enter:종료] ");
				job = s.nextLine();
				if(job.equals("m")||job.equals("M")) {
					do {
						System.out.println("메뉴관리를 선택하시오: [C:메뉴추가] [R:메뉴목톡표시] [U:메뉴수정] [D:메뉴삭제]");
						mjob = s.nextLine();
						if(mjob.equals("c")||mjob.equals("C")) {
							menu.build();
						}else if(mjob.equals("r")||mjob.equals("R")) {
							menu.display();
						}else if(mjob.equals("u")||mjob.equals("U")) {
							menu.modify();
						}else if(mjob.equals("d")||mjob.equals("D")) {
							menu.remove();
						}
					}while(!mjob.equals(""));
				}else if(job.equals("o")|| job.equals("O")) {
					Order order = null;
					do{
						System.out.println("주문작업을 선택하시오:[c:메뉴추가] [r:메뉴목록표시] [d:메뉴삭제]");
						mjob=s.nextLine();
						if(mjob.equals("c")) {
							order = new Order(menu);//class객체를 가져오기 위해서 여기로 와야 한다.
							order.build();
						}else if(mjob.equals("r")){
							order.display();
						}else if(mjob.equals("d")) {
							order.remove();
						}
					}while(!mjob.equals(""));
					System.out.println("마일리지 적립할 모바일 번호를 입력하시오 ['':건너뜀]");
					String mobile = s.nextLine();
					//주문내역->매출내역에 추가
					sales.build(order,mobile);
				}else if(job.equals("s")|| job.equals("S")) {
					sales.getTotal();
				}
			} while(!job.equals(""));
			System.out.println("관리스템 종료");
	}

		static void disPlayMenu(ArrayList<String> alM,ArrayList<Integer> alP){
			for(int i=0;i<alM.size();i++) {
				System.out.println("["+i+"] "+ "["+alM.get(i)+"] "+"["+alP.get(i)+"]");
			}
		}
		static void displayOrder(ArrayList<String> alN,ArrayList<Integer> alC,ArrayList<Integer> alS) {
			for(int i=0; i<alN.size();i++) {
				System.out.println("번호 "+i+" 메뉴 : "+alN.get(i)+" 수량 : "+alC.get(i)+" 총액 : "+alS.get(i));
			}
		}
		

}

<Sales>

import java.util.ArrayList;

public class Sales {
	ArrayList<String> alMobile;
	ArrayList<String> alName;
	ArrayList<Integer> alCount;
	ArrayList<Integer> alSum;

	
	public Sales(){
		this.alMobile = new ArrayList<String>();
		this.alName = new ArrayList<String>();
		this.alCount = new ArrayList<Integer>();
		this.alSum = new ArrayList<Integer>();
		
	}
	public void build(Order order, String mobile) {
		for(int i=0;i<order.alName.size();i++) {//주문내역을 매출내역에 넣기
			this.alMobile.add(mobile);
			this.alName.add(order.alName.get(i));
			this.alCount.add(order.alCount.get(i));
			this.alSum.add(order.alSum.get(i));
		}
	}
	public void getTotal() {
		int total = 0;
		for (int sum : this.alSum) {
			total=total+sum;
		}
		System.out.println("매출총액은 : ["+total+"원] 입니다.");
	}


}

<Menu>

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;//ctrl+shift+O
import java.util.Scanner;

public class Menu {//모양만 만들기때문에 실행문을 쓰지 않는다.
	ArrayList<String> alMenu, alName;
	ArrayList<Integer> alPrice, alCount, alSum;

	Scanner s,s1;
	public Menu() {//초기화
		this.alMenu = new ArrayList<String>();
		this.alPrice = new ArrayList<Integer>();
		s = new Scanner(System.in);
		s1 = new Scanner(System.in);
		
		try {//menu.txt에서 가져온다.
			Scanner fs = new Scanner(new File("d:\\cafe\\menu.txt"));
			while(fs.hasNext()) {//.hasNext() => 안읽는 줄이 있는지 확인하는 함수
				String str = fs.next();
				str.split(",");
				String[] menuitem = str.split(",");
				this.append(menuitem[0], Integer.parseInt(menuitem[1]));//밑에걸로 써도 된다.
//				this.alMenu.add(menuitem[0]);
//				this.alPrice.add(Integer.parseInt(menuitem[1]));//String을 int로 바꿔주는 함수
				
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}
	void save() {
		try {
			File f = new File("d:\\cafe\\menu.txt");
			FileWriter fw = new FileWriter(f);
			for(int i=0;i<this.alMenu.size();i++) {
				String str = this.alMenu.get(i)+","+this.alPrice.get(i)+"\n";
				fw.write(str);
			} 
			fw.close();
		} catch (IOException e) {
				e.printStackTrace();
		}
	}
	
	void build() {
		
		System.out.println("메뉴명을 입력하세요:, [나가기:Enter]");
		String name = this.s.nextLine();
		while(!name.equals("")) {
			System.out.println(name+" 메뉴가격을 입력하세요: ");
			int price = this.s1.nextInt();
			if(price==-1) break;
			this.append(name,price);
			
			System.out.println("메뉴명을 입력하세요:, [나가기:Enter]");
			name = this.s.nextLine();
		}
	}
	void modify() {
		System.out.println("메뉴수정할 번호을 입력하세요, [나가기:-1]");
		this.display();
		int ndx = s1.nextInt();
		while(ndx!=-1) {
			System.out.println("메뉴명 : ");
			String name = s.nextLine();
			System.out.println("가격 : ");
			int price = s1.nextInt();
			this.update(ndx, name, price);
			
			System.out.println("메뉴수정할 번호을 입력하세요, [나가기:-1]");
			this.display();
			ndx = s1.nextInt();
		}
	}
	void remove() {
		System.out.println("삭제할 메뉴 번호를 입력하세요 : ,[나가기:-1]");
		this.display();
			int ndx = s1.nextInt();
		while(ndx!=-1) {
			this.delete(ndx);
			this.display();
			System.out.println("삭제할 메뉴번호, [나가기 -1]");
			ndx=s1.nextInt();
		}
	}
	void append(String name, int price) {//메뉴, 가격 추가
		this.alMenu.add(name); 
		this.alPrice.add(price);
	}
	void display() {//메뉴,가격 리스트 출력
		for(int i=0;i<alMenu.size();i++) {
			System.out.println("["+i+"] "+ "["+alMenu.get(i)+"] "+"["+alPrice.get(i)+"]");
		}
	}
	void delete(int menu_num) {//메뉴, 가격 삭제
		this.alMenu.remove(menu_num);
		this.alPrice.remove(menu_num);
	}
	void update(int menu_num, String name, int price) { //메뉴번호에 새 메뉴명, 새 가격으로 수정
		this.alMenu.set(menu_num, name);
		this.alPrice.set(menu_num, price);
	}
}
File f = new File("d:\\cafe\\menu.txt");
Read new Scanner(f); String str = fs.next(); 읽기(불러오기)
Write new FileWriter(f); fw.write(str); 지우고 쓴 내용 저장
Append new FileWrite(f,true); fw.write(str); 기존 있던거 뒤에 쓴 내용 붙이기
  • File wirter(파일 읽고 쓰기)는 try catch로 묶어야 한다.

<static(전역변수)> : 공유하고 싶을 때 사용 = 어쩔 수 없는 경우에만 사용한다.(잘 사용하지 않음)

ex) static final int pi; = 여기서 'final'이 들어간다면 값을 절대 바꿀 수 없다.

ArrayList <Menu> alMenulist;

=> <Menu> 부분에 String / Integer 이 아니라 class가 들어갈수 있다.

static 예시 그림으로 설명

<접근제한자(Access Modifier)> - 클래스/필드/메소드에 대한 외부의 접근을 제한하는 것

  • public = 전체 접근 가능    protected  = package A와 상속받은 자식 class만 가능   default = package A에서만 가능    private = class I에서만 접근가능

접근할수있는 부분 색으로 표시한 그림

<접근 제한자 예시>

접근제한자 예시

  • 상속 : 부모의 재산을 물려받는 것 
  • 클래스 상속 - 부모(클래스)의 재산(필드, 메소드)을 물려받는 것 but 부모클래스에서 'final' or 'private'을 썼을 경우 자식 클래스에  상속되지 않는다.

부모 클래스와 자식 클래스 설명

<Study18>

public class Study18 {

   public static void main(String[] args) {
   //   CellPhone anycall = new CellPhone();
      DmbCellPhone dcphone = new DmbCellPhone();//코드가 하나도 없지만 상속받아 쓸 수 있다.
      
      dcphone.model="Anycall 2004";
      dcphone.color="silver";
      System.out.println("Model : "+dcphone.model);
      System.out.println("Color : "+dcphone.color);
      
      dcphone.powerOn();
      dcphone.bell();
      dcphone.sendVoice("여보세요");
      dcphone.receiveVoice("누구세요");
      dcphone.hangUp();
      dcphone.powerOff();
   }

}

<CellPhone>

public class CellPhone {

   String model;
   String color;
   
   void powerOn() {
      System.out.println("전원을 켭니다.");
   }
   void powerOff() {
      System.out.println("전원을 끕니다.");
   }
   void bell() {
      System.out.println("벨이 울립니다.");
   }
   void sendVoice(String message) {
      System.out.println("자기 : "+message);
   }
   void receiveVoice(String message) {
      System.out.println("상대방 : "+message);
   }
   void hangUp() {
      System.out.println("전화를 끊습니다.");
   }
}

<DmbCellPhone>

//DmbCellphone이 CellPhone을 상속받았다.
public class DmbCellPhone extends CellPhone {


}

 

  • field 부분은 private
  • getters&setters 부분은 public / default 을 주로 사용

package = 폴더

 

     가상현실(VR)              증강현실(AR)

= 버츄얼 리얼리티        = 배경현실 + 애니매이션(증강)

 

728x90

'Java' 카테고리의 다른 글

2023.01.11  (0) 2023.01.11
2023.01.10  (1) 2023.01.10
2023.01.09 cafe 코드 정리  (0) 2023.01.09
2023.01.06  (0) 2023.01.06
2023.01.05  (0) 2023.01.05

관련글 더보기