0225 Review

KDU·2022년 2월 25일

자바공부

목록 보기
9/17

전역 메서드와 인스턴스 메서드의 이해

  • 전역 메서드
    new 필요없이 사용 가능하나, Static 메모리 영역에 저장된다. Static메모리 영역의 특징은 프로그램이 시작되는 시점부터 끝나는 시점까지 사라지지 않고 유지된다는 점이다. 때문에 Static은 꼭 필요할때만 사용하자.
  • 인스턴스 메서드
    new 를 통해 변수명은 각각의 주소값으로 스택 메모리에, 실제 클래스는 주소마다 각각 힙 메모리에 생성되어 호출되었을 때 힙 메모리에 존재하는 클래스 혹은 값을 읽어서 실행

String으로 간편하게 형변환 하는 방법

String s = i+"";

를 사용하면 좋다.

오늘의 코드

숫자야구 게임을 자바화시켰다.

// 1. 메인 클래스
package chap08;

public class ArrBaseballEx {

	public static void main(String[] args) {

		int[] comArr = new int[3];
		int[] userArr = new int[3];
		int count = 0;

		ArrBaseballLib abl = new ArrBaseballLib();
		abl.makeEachInt(comArr);

		while(true) {
			count++;
			userArr = abl.toArray();
			int[] arr = abl.compareArr(comArr, userArr);
			int strike = arr[0];
			int ball = arr[1];
			int out = arr[2];

			System.out.printf("숫자 '%s%s%s' - Strike:%s, Ball:%s, Out:%s (시도횟수:%s)\n",userArr[0],userArr[1],userArr[2],strike,ball,out,count);
			if(strike==3) {
				System.out.println("게임에서 이겼습니다!");
				break;
			}
			
		}

	}

}
// 2. 숫자야구 메서드 구현
package chap08;

import java.util.Scanner;

public class ArrBaseballLib {

	Scanner scan = new Scanner(System.in);
	
    //컴퓨터가 생성한 세자리 인트값 검수
	public void makeEachInt(int[] a) {
		while(true) {
			for(int i=0; i<a.length; i++) {
				a[i] = (int)(Math.random()*9+1);
			}
			boolean b = true;
			for(int i=0; i<a.length; i++) {
				for(int j=0; j<a.length; j++) {
					if(i != j) {
						if(a[i] == a[j]) {
							b = false;
						}						
					}
				}
			}
			if(b){
				break;
			}
		}
	}
	
    //사람이 입력한 세자리 숫자 검수, 배열화
	public int[] toArray() {
		int[] copyArr = new int[3];

		System.out.println("세자리 숫자를 입력하세요.");
		while(true) {
			String s = scan.next();
			copyArr[0] = s.charAt(0)-'0';
			copyArr[1] = s.charAt(1)-'0';
			copyArr[2] = s.charAt(2)-'0';

			boolean b = true;
			reset:
				for(int i=0; i<copyArr.length; i++) {
					for(int j=0; j<copyArr.length; j++) {
						if(i != j) {
							if(copyArr[i] == copyArr[j]) {
								System.out.println("겹치지 않는 숫자를 입력하세요.");
								b = false;
								break reset;
							}				
						}
					}
					if(copyArr[i] == 0) {
						System.out.println("0을 제외하고 입력하세요.");
						b = false;
						break reset;
					}
				}
			if(b){
				break;
			}
		}

		return copyArr;
	}
	
    //컴퓨터와 사람의 배열 비교
	public int[] compareArr(int[] a, int[] b) {
		
		int strike = 0;
		int ball = 0;
		int out = 0;

		if(a[0]==b[0]) {
			strike++;
		} else if (a[0]==b[1] || a[0]==b[2]) {
			ball++;
		} else {
			out++;
		}

		if(a[1]==b[1]) {
			strike++;
		} else if (a[1]==b[0] || a[1]==b[2]) {
			ball++;
		} else {
			out++;
		}

		if(a[2]==b[2]) {
			strike++;
		} else if (a[2]==b[0] || a[2]==b[1]) {
			ball++;
		} else {
			out++;
		}
		
		int[] arr = new int[3];
		arr[0] = strike;
		arr[1] = ball;
		arr[2] = out;
		
		return arr;
	}

}
profile
의문을 즐깁니다.

0개의 댓글