식당 클래스 설계
1) 명사형과 동사형을 구분한다.
2) 명사형은 변수가 된다.
3) 동사형은 메서드가 된다.
4) 필드는 함부로 접근하면 문제의 소지가 매우 많으므로 일반적으로 외부 접근을 금지시킴(private). class내에서만 접근 가능.
5) 메서드는 일반적으로 외부 호출을 전제로 하기 때문에 일반적으로 접근을 허가함
   public  : 모두 접근 가능 
   default : 같은 패키지에서는 모두 접근 가능 
6) 클래스에는 초기화 작업을 하는 메서드가 존재함. 이 메서드는 객체 생성과 동시에 호출되는 메서드로 "생성자"라 부른다. 만약 생성자를 만들지 않으면 컴파일러가 자동으로 default 생성자를 추가해준다.

 

class Restaurant {
	// 필드(변수): 명사
	private int money = 100000;
	private String[] foods = {"떡볶이", "순대", "라면", "쫄면"};
	private int sel;		// 필드변수는 자동으로 초기화 됨
	
	// 접근 권한을 주지 않으면 default 권한이 적용된다.
	
	
	
	// 생성자의 정의
	// 클래스 이름과 동일
	// 객체 생성시 자동으로 호출(초기화 작업을 담당)
	Restaurant(){
		System.out.println("--생성자 호출--");
		cleaning();
		prepareFoods();
	}
	
	
	// 메서드(기능): 동사
	// Method중에 외부에서 호출될 필요가 없는 것은
	// private으로 선언한다.
	private void cleaning() {
		System.out.println("식당을 청소한다");
	}
	private void prepareFoods() {
		System.out.println("음식 재료를 손질하다");
	}
	private void calcMoney() {
		System.out.println("오늘 돈은 " + money + "이다");
	}
	
	void welcome() {
		System.out.println("어서 오세요");
	}
	void byeBye() {
		System.out.println("안녕히가세요");
	}
	void getMoney(int m) {
		if(m < 0) {
			System.out.println("음식값을 주세요");
			return;
		}
		money += m;
		System.out.println(m + "을 음식값으로 받음");
	}

	void anyFood() {
		System.out.println("어떤 음식 드실래요?");
		System.out.println(Arrays.toString(foods));
		Random rd = new Random();
		sel = rd.nextInt(foods.length);
		System.out.println(foods[sel] + "이요");
	}
	void cookFood() {
		System.out.println(foods[sel] + "을 요리하다");
	}
	void sendFood() {
		System.out.println(foods[sel] + "나왔습니다");
		System.out.println("맛있게 드세요");
	}
	void finishWork() {
		calcMoney();
		cleaning();
	}
}

public class RunRestaurant{
	public static void main(String[] args) {
		Restaurant rest = new Restaurant();
		//새로운 레스토랑객체를 만들어서 레스트에 담는다.
		//변수식이랑 똑같음
		
		// 본격적으로 손님이 오기전에 할 일 → 어차피 식당을 열기 전에 해야할 초기화 작업이라면 아래처럼 하지 않고 생성자를 이용한다.
		//rest.cleaning();
		//rest.prepareFoods();
		
		// 손님오면 맞이하기
		for(int i=0;i<10;i++) {
			System.out.println("-------------------");
			rest.welcome();
			//if(i==5) 
			//rest.foods = new String[] {"쥐", "바퀴벌레"}; //이러한 경우를 막기 위해 private변수로 설정
			rest.anyFood();
			rest.cookFood();
			rest.sendFood();
			rest.getMoney(9000);
			//rest.money = -10000000; //이러한 경우를 막기 위해 private변수로 설정
			rest.byeBye();
			System.out.println("-------------------");
		}
		
		// 하루를 마치고 해야 할 일
		rest.finishWork();
		//rest.calcMoney();
		//rest.cleaning();
	}	
}

 

'java' 카테고리의 다른 글

Java/ Static의 개념과 응용  (0) 2020.02.10
Java/ 클래스간의 상호관계  (0) 2020.02.10
Java/Def of Class/클래스정의  (0) 2020.01.28
Java/Recursion/재귀호출  (0) 2020.01.28
Java/Linear Search/선형검색  (0) 2020.01.28

프로그래밍 = 변수 + 연산자 + 제어문
프로그래밍의 규모가 커짐 → 절차지향 프로그래밍의 필요성

동작위주의 메서드 독립단위의 모듈


Class = 변수(명사/상태/특성) + 메서드(동사/기능/행동)
ex)

클래스 몽실

몽실이의 생김새, 특성=변수

몽실이의 동작=메서드

public class Puppy {
	
	// 인스턴스 변수
	public String name;
	public String leftEye = "왼쪽 눈";
	public String rightEye = "오른쪽 눈";
	public String mouth = "입";
	public String nose = "코";
	public String tail = "꼬리";
	public String[] legs = new String[4];
	
	// 인스턴스 메서드
	public void pretty() {
		System.out.println(name+"가 " + tail + "을 흔든다");
	}
	public void eat() {
		System.out.println(name+"가 " + nose + "을 킁킁 거린다");
		System.out.println(name+"가 " + mouth + "을 벌려서 먹는다");
	}
	public void sleep() {
		System.out.println(name+"가 " + leftEye + "을 감는다");
		System.out.println(name+"가 " + rightEye + "을 감는다");
	}
	
	
	
	
    // main의 역할은 "프로그램의 시작"
	// 다만 Puppy객체가 만들어져 있지 않아도 무조건 메모리에 로딩되어야 하므로
	// main에 static 키워드를 붙여서 시스템이 실행되면 무조건 메모리로 
       main메서드를 올리게 된다.
	
	// static이 아닌 일반 메서드는 해당 객체가 생성될 때
	// 메모리에 로딩되게 된다.
    
    
	public static void main(String[] args) {
		Puppy mongsil = new Puppy();
		mongsil.name = "몽실이";
		
		Puppy baekgu = new Puppy();
		baekgu.name = "백구";
		
		mongsil.pretty();
		baekgu.pretty();
	}
}

 

'java' 카테고리의 다른 글

Java/ 클래스간의 상호관계  (0) 2020.02.10
Java/Class exc/클래스 응용  (0) 2020.01.28
Java/Recursion/재귀호출  (0) 2020.01.28
Java/Linear Search/선형검색  (0) 2020.01.28
Java/Bubble Sort/버블정렬  (0) 2020.01.28

재귀 메서드는 반복되는 호출속에서 탈출조건이 매우 중요하다.
탈출 조건이 정확하지 않으면 무한 루프가 돌면서 스택 오버 플로우 현상이 나타난다.

 

이미지참조

https://www.cdn.geeksforgeeks.org/wp-content/uploads/Recursive-Functions-in-c.png

 

 

public class RecallAlphabet {
	public static void recallAlphabet(char[] arr, int len) {
		for(int i=0;i<len;i++)
			System.out.print(arr[i]);
		System.out.println();
		
		if(len == 1)
			return;
		else
			recallAlphabet(arr, --len);
	}
	
	public static void main(String[] args) {
		char[] alpha = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'};
//		String strAlpha = "abcdefgh";
//		char[] alpha = strAlpha.toCharArray();
		
		recallAlphabet(alpha, alpha.length);
	}
}
abcdefgh
abcdefg
abcdef
abcde
abcd
abc
ab
a

 

public class RecallAlphabet1 {
	public static void recallAlphabet(char ch) {
		for(int i = (int)'a';i<=(int)ch;i++) {
			System.out.print((char)i);
		}
		System.out.println();
		
		if(ch == 'a')
			return;
		else
			recallAlphabet((char)(((int)ch)-1));
	}
	
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.print("type one character : ");
		char ch = sc.next().charAt(0);
		recallAlphabet(ch);
		sc.close();
	}

}
type one character : r
abcdefghijklmnopqr
abcdefghijklmnopq
abcdefghijklmnop
abcdefghijklmno
abcdefghijklmn
abcdefghijklm
abcdefghijkl
abcdefghijk
abcdefghij
abcdefghi
abcdefgh
abcdefg
abcdef
abcde
abcd
abc
ab
a

'java' 카테고리의 다른 글

Java/Class exc/클래스 응용  (0) 2020.01.28
Java/Def of Class/클래스정의  (0) 2020.01.28
Java/Linear Search/선형검색  (0) 2020.01.28
Java/Bubble Sort/버블정렬  (0) 2020.01.28
Java/Binary Search/이진탐색  (0) 2020.01.28

Linear search

: sequentially checks each element of the list until a match is found or the whole list has been searched.

Linear search is rarely practical because other search algorithms and schemes, such as the binary search algorithm and hash tables, allow significantly faster searching for all but short lists.

 

선형검색

: 속도가 느리고 비효율적이기 때문에 대용량의 데이터를 처리하는 곳에는 쓰지 않는다.

 

이미지참조

https://www.cdn.geeksforgeeks.org/wp-content/uploads/Linear-Search.png

 

//Given an array arr[] of elements, write a function to search a given element x in arr[]

// 배열을 20개 숫자를 초기화 한다
// 특정 숫자가 index 몇번에 있는 지 반환하는 메서드
// 없으면 -1을 반환한다.


public class LinearSearch {
	 public static int linearSearch(int[] arr, int num) {
		 int idx = -1;
		 for(int i=0;i<arr.length;i++) {
			 if(num == arr[i]) {
				 System.out.println("찾았다");
				 idx = i;
				 break;
			 }			 
		 }
		 return idx;
	 }
	 
	 public static void main(String[] args) {
		 int[] arr = {23, 22, 6, 62, 87, 12, 99, 88, 72, 1,
				 	  21, 5, 26, 73, 38, 46, 29, 56, 52, 2};
		 Scanner sc = new Scanner(System.in);
		 while(true) {
			 System.out.print("검색 숫자 입력 (-1이면 exit) : ");
			 int num = sc.nextInt();
			 if(num == -1)
				 break;
			 int idx = linearSearch(arr, num);
			 if(idx == -1)
				 System.out.println("찾을 수 없습니다");
			 else {
				 //System.out.printf("index %d에 있습니다\n", idx);
				 System.out.printf("%d번째 있습니다\n", idx+1);
			 }
		 }
		 System.out.println("종료합니다");
		 sc.close();
		 
	}
}

'java' 카테고리의 다른 글

Java/Def of Class/클래스정의  (0) 2020.01.28
Java/Recursion/재귀호출  (0) 2020.01.28
Java/Bubble Sort/버블정렬  (0) 2020.01.28
Java/Binary Search/이진탐색  (0) 2020.01.28
Java/Selection Sort/선택정렬  (0) 2020.01.28

Bubble Sort

: compares all the element one by one and sort them based on their values.

 

 

이미지참조

https://user-images.githubusercontent.com/1997137/63668342-6c5ff680-c809-11e9-80f6-fa7e80959dec.png

 

public class _3BubbleSort {
	public static int[] bubbleSort(int[] list) {
		for (int i = 0; i < list.length; i++) {//처음 고정의 역할
			for (int j = 0; j < list.length - 1 - i; j++) {
				if (list[j] > list[j + 1]) {//j를 기준점으로 j+1의 자리와 비교
					int temp = list[j];
					list[j] = list[j + 1];
					list[j + 1] = temp;
				}
			}
		}
		return list;
	}

	public static void main(String[] args) {
		int [] list= {10,44,3,64,6,21,68,365,99};
		System.out.println(Arrays.toString(list));
		bubbleSort(list);
		System.out.println(Arrays.toString(list));
	}
}

Binary search 

: compares the target value to the middle element of the array. If they are not equal, the half in which the target cannot lie is eliminated and the search continues on the remaining half, again taking the middle element to compare to the target value, and repeating this until the target value is found. If the search ends with the remaining half being empty, the target is not in the array.

 

이진탐색

: 대용량의 데이터 효율으로 검색하는데 유용->검색속도의 절감.

 

이미지참조

https://www.geeksforgeeks.org/wp-content/uploads/Binary-Search.png

package edu.exam03.binarysearch;

import java.util.Arrays;
import java.util.Scanner;

public class BinarySearch {
	public static int binarySearch(int[] arr, int num) {
		int compIdx = -1;   // 2등분 위치, 찾는 위치
		int first = 0, last = arr.length-1;
		int cnt = 0;	// 몇번만에 검색했니?
		while(true) {
			cnt++;	// 1회씩 검색 증가in
			compIdx = first + (last - first)/2;
			
			if(last == first) {
				if(arr[first] == num){
					System.out.printf("%d회 찾았다!", cnt);
					break;
				}else {
					System.out.printf("%d회 못 찾았다!", cnt);
					compIdx = -1;
					break;
				}
			}
			
			if(arr[compIdx] == num) {
				System.out.printf("%d회 찾았다!", cnt);
				break;
			}else if(arr[compIdx] < num) {
				first = compIdx+1;
			}else {
				last = compIdx-1;
			}
		}
		
		return compIdx;
	}

	 public static void main(String[] args) {
		 int[] arr = {23, 22, 6, 62, 87, 12, 99, 88, 72, 1,
				 	  21, 5, 26, 73, 38, 46, 29, 56, 52, 2};
		 Scanner sc = new Scanner(System.in);
		 Arrays.sort(arr);		// 이진 검색에서는 정렬을 해야만 한다
		 System.out.println(Arrays.toString(arr));
		 while(true) {
			 System.out.print("검색 숫자 입력 (-1이면 exit) : ");
			 int num = sc.nextInt();
			 if(num == -1)
				 break;
			 int idx = binarySearch(arr, num);
			 if(idx == -1)
				 System.out.println("찾을 수 없습니다");
			 else {
				 //System.out.printf("index %d에 있습니다\n", idx);
				 System.out.printf("%d번째 있습니다\n", idx+1);
			 }
		 }
		 System.out.println("종료합니다");
		 sc.close();
		 
	}

}

 

 

 

Selection sort 

: is noted for its simplicity, and it has performance advantages over more complicated algorithms in certain situations, particularly where auxiliary memory is limited.

The algorithm divides the input list into two parts: the sublist of items already sorted, which is built up from left to right at the front (left) of the list, and the sublist of items remaining to be sorted that occupy the rest of the list. Initially, the sorted sublist is empty and the unsorted sublist is the entire input list. The algorithm proceeds by finding the smallest (or largest, depending on sorting order) element in the unsorted sublist, exchanging (swapping) it with the leftmost unsorted element (putting it in sorted order), and moving the sublist boundaries one element to the right.

 

선택정렬

:적은 데이터를 정렬하는데 유용. 

 

참조이미지

https://www.w3resource.com/w3r_images/selection-sort.png

import java.util.Arrays;

public class SelectionSort {
	
	public static void selectionSort(int[]_arr) {
		//마지막값은 비교대상이 없으므로 배열길이 -1까지만 비교가 이루어진다.
		for(int i=0;i<_arr.length-1;i++) {//i를 기준점으로 j와 비교
			int minIdx=i;
			
			//아래 for문이 끝나면 현재기준공간에 들어갈 위치가 결정된다.
			for (int j=i+1;j<_arr.length;j++) {
				if(_arr[j]<_arr[minIdx])//부등호에 따라 내림차순 오름차순 결정.
					minIdx=j;
					
			}
			//_arr배열의 i값과 minIdx값을 교체한다.
			swap(_arr,i,minIdx);
			
		}
	}
	public static void swap(int[]_a, int base, int mIdx) {
		int temp=_a[base];
		_a[base]=_a[mIdx];
		_a[mIdx]=temp;
		
	}
	
	public static void main(String[] args) {
		int[] arr= {77,99,25,2,10};
		System.out.println(Arrays.toString(arr));
		selectionSort(arr);
		System.out.println(Arrays.toString(arr));
		
		int[] arr1= {77,99,25,2,10,4,523,244,22,1,3};
		System.out.println(Arrays.toString(arr1));
		selectionSort(arr1);
		System.out.println(Arrays.toString(arr1));
	}
}
public class VariableLocal {

	public static Random rd = new Random();
	public static int num = 0; // Static=Class Variable

	public static void method0() {
		System.out.println("method0: " + num);
		num = rd.nextInt(100);
		System.out.println("method0: " + num);
	}

	public static int method1() {
		int num = 0; // Local Varialble
		System.out.println("method1: " + num);
		num = rd.nextInt(100);
		System.out.println("method1: " + num);
		return num;//return num of Local Varialble

	}

	public static void main(String[] args) {
		method0();
		System.out.println("num:" + num);
		int temp = method1();// get num of Local Varialble
		System.out.println("temp:" + temp);
		System.out.println("num:" + num);

	}
}
method0: 0
method0: 93
num:93
method1: 0
method1: 47
temp:47
num:93

'java' 카테고리의 다른 글

Java/Binary Search/이진탐색  (0) 2020.01.28
Java/Selection Sort/선택정렬  (0) 2020.01.28
Java/Static variable/스태틱변수, 클래스변수  (0) 2020.01.28
Java/Local Variable/지역변수  (0) 2020.01.28
Java/Swap values and arrays  (0) 2020.01.27