June is Combung

배열 컨트롤 기본예제 본문

java/배열

배열 컨트롤 기본예제

june__Park 2021. 3. 23. 10:33
package week2;

import java.util.Scanner;

public class Day11_3 {

	public static void main(String[] args) {
		// 문제1) 추가 를 선택하고 값을 입력하면 10 , 20 뒤에 저장한다.
		// 최대 5개까지 저장
		Scanner scan = new Scanner(System.in);
		// 0 1 2 3 4
		int[] arr = { 10, 20, 50, 60, 0 };
		int cnt = 4; // 실질적으로 들어간 값 : 방번호 +1
		boolean run = true;
		while (run) {
			for (int i = 0; i < cnt; i++) {
				System.out.print(arr[i] + " ");
			}
			System.out.println();
			System.out.println("[1]추가");
			System.out.println("[2]삭제(인덱스)");
			System.out.println("[3]삭제(값)");
			System.out.println("[4]삽입");
			System.out.println("[5]종료");
			System.out.println("메뉴 선택 : ");
			int sel = scan.nextInt();
			if (sel == 1) {
				if (cnt >= 5) {
					System.out.println("더이상 값을 추가할 수 없습니다");
					continue; // 반복문의 처음으로 돌아가
				}
				System.out.println("추가할 값 입력 : ");
				int value = scan.nextInt();
				arr[cnt] = value; // 추가
				arr[2] = 0; // 삭제 : 0으로 초기값 만들어줌
				cnt++;
			} else if (sel == 2) {
				System.out.println("삭제할 인덱스 입력 : ");
				int del_idx = scan.nextInt();
				if (del_idx < 0 || del_idx >= cnt) {
					System.out.println("유효하지 않는 인덱스 입니다  ");
					continue;
				}
				for (int i = del_idx; i < cnt - 1; i++) {
					arr[i] = arr[i + 1];
					// 왼쪽 변수에 오른쪽의 값을 넣어준다
				}
				cnt--; // 실제 값 -1 되었으니 카운트 감소
				arr[cnt] = 0;
			} else if (sel == 3) {
				System.out.println("삭제할 값 입력 : ");
				int del_value = scan.nextInt();
				int del_idx = -1;
				for (int i = 0; i < cnt; i++) {
					if (arr[i] == del_value) {
						del_idx = i;
						break;
					}
				}
				if (del_idx == -1) {
					System.out.println("유효하지 않는 값 입니다  ");
					continue;
				}
				for (int i = del_idx; i < cnt - 1; i++) {
					arr[i] = arr[i + 1];
					// 왼쪽 변수에 오른쪽의 값을 넣어준다
				}
				cnt--; // 실제 값 -1 되었으니 카운트 감소
				arr[cnt] = 0;
			} else if (sel == 4) {
			} else {
				break;
			}
		}

	}

}

'java > 배열' 카테고리의 다른 글

배열 컨트롤 기본예제2  (0) 2021.03.23
얕은복사와 깊은복사  (0) 2021.03.23
배열 컨트롤러  (0) 2021.03.23
사다리게임  (0) 2021.03.23
틱택토  (0) 2021.03.23
Comments