본문 바로가기
IT 이야기/Java

[Java Study] 4일차 선택문,조건문, junit5.. 그리고 트리 구조

by Dblog 2020. 12. 5.
728x90

선택문

Switch

Switch를 표현하는 선택문은 다중 if를 보완하는데 효과적으로 사용할 수 있습니다.
JAVA도 C, C++에서 쓰이는 형태와 비슷하게 사용되고 있습니다.

- switch문의 표현식은 프리미티브 타입, 래퍼런스 타입 모두 사용이 가능합니다.
- switch 의 () 사이에 변수 또는 표현식을 사용할 수 있습니다.
- case, default 구조를 선택할 수 있습니다.
- 각 case는 중복값을 사용해선 안됩니다.
- 선택적으로 break, yeild를 사용할 수 있습니다.


C, C++ 와 다른점

  • case -> A 형식의 lambda 표현 지원
  • yeild 키워드 적용

이전 3일차에서 공부했지만 case, yeild는 java12, 13을 거치며 적용된 부분입니다.

- 예제 코드

int switchVal;
int value = 0;

switch(switchVal){
	case 1:
    	break;
    case 2:
    	yeild;
    case 3 --> add():
    case 4:
	default:
    	value = 1;
}

 


 

If else

if else에 대해 제어문 영역으로 나누는 책이 있지만 if else 도 선택문의 한 종류로 보는 책도 있습니다.
if 조건에 따라 if 와 else로 선택됩니다.

if (조건) {
	System.out.println("조건 true");
}
else {
	System.out.println("조건 false");
}

반복문

for

같은 코드를 반복할때 사용합니다. 반복 횟수는 미리 정의된 조건만큼만 반복합니다. for(;;)의 경우는 예외로 for 안의 코드를 무한 반복 합니다. 

반복문은 단어 그대로 같은 작업을 반복시켜주는 문법

- 기본형태  for(초기값;조건;증감)

for(int i=0; i < 10; i++){
	// 반복할 작업
}

 

while

조건이 만족될 때 까지 코드가 반복되어 실행됩니다. 조건이 거짓이 되는 순간, 코드 내에 break, return을 만나는 순간 반복이 중지 됩니다.

- 기본 형태 while(조건)

while( i > 10){
	//반복 구문
    i++;
}

 

 

JUnit 5

https://dblog94.tistory.com/entry/Java-JUnit5

 

[Java] JUnit5

https://junit.org/junit5/ JUnit 5 Société Générale Use, Contribute and Attract: learn about Société Générale's open source strategy. junit.org JUnit 자바의 소스를 테스트할때 가장 많이 사용하..

dblog94.tistory.com

 

live-study 대시 보드를 만드는 코드를 작성

  • 깃헙 이슈 1번부터 18번까지 댓글을 순회하며 댓글을 남긴 사용자를 체크 할 것.
  • 참여율을 계산하세요. 총 18회에 중에 몇 %를 참여했는지 소숫점 두자리가지 보여줄 것.
  • Github 자바 라이브러리를 사용하면 편리합니다.
  • 깃헙 API를 익명으로 호출하는데 제한이 있기 때문에 본인의 깃헙 프로젝트에 이슈를 만들고 테스트를 하시면 더 자주 테스트할 수 있습니다.

 

LinkedList 구현

  • ListNode add(ListNode head, ListNode nodeToAdd, int position)
  • ListNode remove(ListNode head, int positionToRemove)
  • boolean contains(ListNode head, ListNode nodeTocheck)
구현
package test;

//ListNode add(ListNode head, ListNode nodeToAdd, int position)를 구현하세요.
//ListNode remove(ListNode head, int positionToRemove)를 구현하세요.
//boolean contains(ListNode head, ListNode nodeTocheck)를 구현하세요.


class ListNode{
	int data;
	ListNode next;
	
	public ListNode() {}
	
	public ListNode(int data) {
		this.data = data;
		this.next = null;
	}
	
	public ListNode add (ListNode head, ListNode nodeToAdd, int position) {
		ListNode ListNode = head;
		
		if (position != 0) {
			for(int i=0; i < position-1; i++) {
				ListNode = ListNode.next;
			}
			nodeToAdd.next = ListNode.next;
			ListNode.next = nodeToAdd;
		}
		else {
			nodeToAdd.next = head;
			head = nodeToAdd;
		}
		
		return head;
	}
	
	public ListNode remove(ListNode head, int position) {
		ListNode node = head;
		
		if (position == 0) {
			head = node.next;
			return head;
		}
		
		for(int i=0; i < position -1; i++) {
			node = node.next;
		}
		
		ListNode del = node.next;
		node.next = del.next;
		return head;
	}
	
}



 

테스트 코드
public class NodeTest{
	public static void main(String[] args) {
		ListNode listed= new ListNode();
		
		
		ListNode a= new ListNode(1);
		ListNode b= new ListNode(2);
		ListNode c= new ListNode(3);
		ListNode d= new ListNode(4);
		ListNode e= new ListNode(5);
		
		listed = a;
		a.next = b;
		b.next = c;
		c.next = d;
		d.next = e;
		
		listed = listed.add(listed, new ListNode(5533), 4);
		listed = listed.remove(listed, 2);

		while(test1 != null) {
			System.out.println(listed.data);
			listed = listed.next;
		}
		
	}
	
}

 

Stack을 구현

  • int 배열을 사용해서 정수를 저장하는 Stack을 구현하세요.
  • void push(int data)를 구현하세요.
  • int pop()을 구현하세요.

stack은 자료구조 중 하나로 LIFO(Last In First Out)의 구조를 가지고 있습니다.
push를 하면 제일 아래 부터 쌓이는 형태로 표현할 수 있습니다. 아래 부터 쌓이는 형태로 표현하는 것은 추후 pop의 설명의 용이성입니다.

(1, 2, 3, 4) 4개의 숫자를 push 하고 5를 추가로 push 하려고 시도 하여도 메모리에 공간이 없기 때문에 5는 저장 되지 않습니다. 메모리 Full에 대해서는 구현에 따라 에러를 리턴하도록 구현할 수 있습니다.

자료를 담고 자료를 얻어내기 위해서 pop을 사용하게 되는데 pop은 가장 최근에 push한 데이터 즉, 최 상단 데이터를 리턴하고 메모리 상단을 비워 주게 됩니다. 

 


 

구현
class Stack {
	private int[] stack = new int[5];
	int maxCount = 0;
	
	public int[] push(int data) {
		if(maxCount > 4) {
			System.out.println("stack is full didn't push");
			return stack;			
		}
		else {
			stack[maxCount] = data;
			maxCount++;
			return stack;
		}		
	}
	
	public int pop() {
		if (maxCount < 0) {
			System.out.println("stack is empty");
			return -1;
		}
		else {
			maxCount--;
			return stack[maxCount];
		}		
	}
    
    public static void main(String[] args) {
		Stack testCode = new Stack();
		testCode.push(0);
		testCode.push(1);
		testCode.push(2);
		testCode.push(3);
		testCode.pop();
		testCode.pop();
		testCode.push(4);
		testCode.push(5);
		testCode.push(6);
		
		for(int i=0; i < testCode.maxCount; i++) {
			System.out.println(testCode.stack[i]);
		}
	}
}

 

 

ListNode를 사용한 Stack을 구현

  • ListNode head를 가지고 있는 ListNodeStack 클래스를 구현하세요.
  • void push(int data)를 구현하세요.
  • int pop()을 구현하세요.

 

Queue 구현

  • 배열을 사용한 구현
public class Queue {
	private int[] queue = new int[6];
	private int maxQueueCount = 0;
	
	void  insert(int data) {
		if (maxQueueCount > 4) {
			System.out.println("queue is full");
			return;
		}
		else {
			for(int i=maxQueueCount; i > -1; i--) {
				queue[i+1] = queue[i];
			}
			queue[0] = data;
			maxQueueCount++;
		}
	}
	
	int peek() {
		return queue[maxQueueCount-1];
	}
	
	int remove() {
		int target = queue[maxQueueCount-1];
		maxQueueCount--;
		return target;
	}
    
    //test code
    public static void main(String[] args) {
		Queue testCode = new Queue();
		testCode.insert(1);
		testCode.insert(2);
		testCode.insert(3);
		testCode.insert(4);
		testCode.insert(5);
		testCode.remove();
		testCode.insert(6);
		
		for(int i=0; i < testCode.maxQueueCount; i++) {
			System.out.println(testCode.queue[i]);
		}
		System.out.println("peek");
		System.out.println(testCode.peek());
		
	}
}

 

  • ListNode를 사용한 구현
728x90

댓글