U E D R , A S I H C RSS

Java Study2002/영동-3주차

JavaStudy2002의 3주차 과제
Starter: Yggdrasil


  • 음... 우선 도스창에서 입력받아서 이동시키는 것만 빼면 다 했습니다. 그 입력이 C처럼 만만하지가 않더군요... 입력 하나 받는데 뭘 그렇게 많이 써야 하는지...
  • 우선 상민이형이 써 주신 것에서 1번을 해 보았습니다.(버그 수정 완료)...이제 2번 할 차례...그리고 어쩌다가 count변수가 다시 필요해져서 다시 넣었습니다.

* 헉 참고의 의미였는데.. 뭐 해보는것도 좋을것 같습니다. 지금 디자인을 유지하고 3번째 까지 시도하신다면, count 변수는 자연스럽게 사라질것입니다.

3번째의 코드는 comment solving을 보인거니 감안하십시오. 3번을 그대로 한다면, 입력 데이터와, Bug 사이의 인터페이스를 맞추는 함수가 필요할것입니다.

사소한 것이지만 지적한다면 class main 의 이름을 Main 으로 바꾸시기를 강력(?) 추천합니다. Java 에는 지켜야하는 규칙인 문법외에 코딩 약속을 추천하고 있씁니다. 과거 MS라면 헝가리안표기법 이겠지요? 현재의 .net 에서 헝가리안표기법은 없어졌습니다. --neocoin

Class main
~cpp 
import java.util.*;  
public class main{  
    public static void main(String[] args)  
    {  
        Bug bug1=new Bug(); 
        System.out.println("RandomWalk");
        bug1.journey[0]='0';   
        bug1.journey[1]='0';   
        bug1.journey[2]='4';   
        for(int i=0;bug1.journey[i]!='\0';i++) 
        	bug1.move(bug1.journey[i]);
    } 
}  
Class Bug
~cpp 
public class Bug{ 
    public int x=0;  
    public int y=0;
    public int count=0;  
    public char journey[]={'\0','\0','\0','\0','\0'}; 
    Board aboard=new Board(); 
    
    public void move(char way)  
    {             
    	if(count==0)
    		aboard.board[0][0]++;            
        if(way=='0')//북     
        	x=x-1;  
        else if(way=='1')//북동  
        {    
        	x=x-1;  
            y=y+1;
        }
        else if(way=='2')//동  
        	y=y+1;    
        else if(way=='3')//남동  
        {  
          	x=x+1;  
            y=y+1;  
        }  
        else if(way=='4')//남  
          	x=x+1;  
        else if(way=='5')//남서  
        {  
        	x=x+1;  
            y=y-1;  
        }  
        else if(way=='6')//서      
         	y=y-1;     
        else if(way=='7')//북서  
        {
        	x=x-1;  
            y=y-1;  
        } 
        if(x>=aboard.board.length)
        	x=0;
        if(x<0)
        	x=aboard.board.length-1;
        if(y>=aboard.board[0].length)
        	y=0;
        if(y<0)
        	y=aboard.board[0].length-1;
       		
       	aboard.board[x][y]++;   
              
        aboard.exhibit();  
        System.out.print("\n");   
        count++;    
	}  
} 
Class Board
~cpp 
public class Board{ 
    public int board[][]={  
                {0,0,0,0,0},  
                {0,0,0,0,0},  
                {0,0,0,0,0},  
                {0,0,0,0,0},  
                {0,0,0,0,0}  
    };                     
    public void exhibit(){  
		for(int i=0;i<board.length;i++)  
		{  
    		for(int j=0;j<board.length;j++){  
        		System.out.print(board[i][j]);  
        		System.out.print("\t");  
        	}  
        System.out.print("\n");  
    	}  
    }  
} 

1차로 참고

  • 변경사항은 각 주석에서 설명합니다.
  • word rap 하는 부분의 중복을 제거 했습니다.
  • 안쓰이는 Board.count 인자 제거

~cpp 
public class Board {
	public char journey[] =
		{ '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0' };
	public int x = 0;
	public int y = 0;
	public int board[][] = { { 0, 0, 0, 0, 0 }, {
			0, 0, 0, 0, 0 }, {
			0, 0, 0, 0, 0 }, {
			0, 0, 0, 0, 0 }, {
			0, 0, 0, 0, 0 }
	};

	public void move(char way) {

		if (way == '0') //북
			{
			x = x - 1;
		} else if (way == '1') //북동  
			{
			x = x - 1;
			y = y + 1;
		} else if (way == '2') //동  
			{
			y = y + 1;
		} else if (way == '3') //남동 
			{
			y = y + 1;
			x = x + 1;
		} else if (way == '4') //남  
			{
			x = x + 1;
		} else if (way == '5') //남서		  
			{
			y = y - 1;
			x = x + 1;
		} else if (way == '6') //서  
			{
			y = y - 1;
		} else if (way == '7') //북서  
			{
			y = y - 1;
			x = x - 1;
		}
		
		// WordRap 을 여기에서 수행
		if (x >= board.length)
			x = 0;
		if (y >= board[0].length)
			y = 0;
		if (x < 0)
			x = board.length - 1;
		if (y < 0)
			y = board[0].length - 1;
		board[x][y]++;
		exhibit();
		System.out.println();
	}

	public void exhibit() {
		// Magic Number 제거
		for (int i = 0; i < board.length; i++) {
			for (int j = 0; j < board[i].length; j++) {
				System.out.print(board[i][j] + "\t");				
			}
			System.out.println();
		}
	}

	public static void main(String[] args) {
		Board aboard = new Board();
		System.out.println("RandomWalk");
		aboard.board[0][0]++;

		aboard.journey[0] = '0';
		aboard.journey[1] = '3';

		for (int i = 0; aboard.journey[i] != '\0'; i++)
			aboard.move(aboard.journey[i]);

	}

}

2차 참고

  • HashMap 을 이용해서 방향값에 대한 값의 변화량을 넣습니다. 이전에 배열로 구현하여 코드를 짧게 하는 것과 같은 목적입니다.

~cpp 
import java.util.HashMap;

public class Board {
	public char journey[] =
		{ '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0' };
	public int x = 0;
	public int y = 0;
	public int board[][] = { { 0, 0, 0, 0, 0 }, {
			0, 0, 0, 0, 0 }, {
			0, 0, 0, 0, 0 }, {
			0, 0, 0, 0, 0 }, {
			0, 0, 0, 0, 0 }
	};

	class 방향값 {
		방향값(int x, int y) {
			this.x = x;
			this.y = y;
		}
		int x;
		int y;
	}
	public void move(char way) {
		// HashMap 을 이용해서 변화량만을 추가
		HashMap directionMap = new HashMap();

		directionMap.put("0", new 방향값(-1, 0)); // 북		
		directionMap.put("1", new 방향값(-1, 1)); // 북동		
		directionMap.put("2", new 방향값(0, 1)); // 동		
		directionMap.put("3", new 방향값(1, 1)); // 남동		
		directionMap.put("4", new 방향값(1, 0)); // 남		
		directionMap.put("5", new 방향값(1, -1)); // 남서		
		directionMap.put("6", new 방향값(0, -1)); // 서		
		directionMap.put("7", new 방향값(-1, -1)); // 북서

		// primitive type 을 String(Object) 으로 변경하는 꽁수
		// HashMap 에 입력된 방향 델타 값을 얻어내어 x,y 더함
		방향값 delta = (방향값) directionMap.get("" + way);
		x += delta.x;
		y += delta.y;

		// Wordrap 코드 수정
		x = (x >= board.length) ? 0 : x;
		y = (y >= board[0].length) ? 0 : y;		
		x = (x < 0) ? board.length - 1 : x;
		y = (y < 0) ? board[0].length - 1 : y;

		board[x][y]++;
		// exhibit -> printBoard 로 rename
		printBoard();
		System.out.println();
	}

	public void printBoard() {
		// Magic Number 제거
		for (int i = 0; i < board.length; i++) {
			for (int j = 0; j < board[i].length; j++) {
				System.out.print(board[i][j] + "\t");
			}
			System.out.println();
		}
	}

	public static void main(String[] args) {
		Board aboard = new Board();
		System.out.println("RandomWalk");
		aboard.board[0][0]++;

		aboard.journey[0] = '0';
		aboard.journey[1] = '3';

		for (int i = 0; aboard.journey[i] != '\0'; i++)
			aboard.move(aboard.journey[i]);

	}
}

3차 참고

  • char jouney -> ArrayList 로 대체
  • x, y -> nowX, nowY 로 rename : 의미상으로 currentXPos가 적당하겠지요.
  • 방향을 표현하는 Magic number 제거, 여정인 Board.jouney 가 ArrayList 이므로, String을 넣습니다. 일종의 comment mixing이 되겠지요.


~cpp 
import java.util.ArrayList;
import java.util.HashMap;

public class Board {	
	// char jouney -> ArrayList 로 대체	
	protected ArrayList jouney = new ArrayList();
	
	// x -> nowX	
	public int nowX = 0;
	// y -> nowY
	public int nowY = 0;
	public int board[][] = { { 0, 0, 0, 0, 0 }, {
			0, 0, 0, 0, 0 }, {
			0, 0, 0, 0, 0 }, {
			0, 0, 0, 0, 0 }, {
			0, 0, 0, 0, 0 }
	};

	class 방향값 {
		방향값(int x, int y) {
			this.x = x;
			this.y = y;
		}
		int x;
		int y;
	}
	public void move(String way) {
		// HashMap 을 이용해서 변화량만을 추가
		HashMap directionMap = new HashMap();

		// 방향에 있는 Magic number 제거
		directionMap.put("북", new 방향값(-1, 0));
		directionMap.put("북동", new 방향값(-1, 1));
		directionMap.put("동", new 방향값(0, 1));
		directionMap.put("남동", new 방향값(1, 1));
		directionMap.put("남", new 방향값(1, 0));
		directionMap.put("남서", new 방향값(1, -1));
		directionMap.put("서", new 방향값(0, -1));
		directionMap.put("북서", new 방향값(-1, -1));
		
		// primitive type 을 String(Object) 으로 변경하는 꽁수
		// HashMap 에 입력된 방향 델타 값을 얻어냅니다.
		방향값 delta = (방향값) directionMap.get("" + way);

		nowX += delta.x;
		nowY += delta.y;

		// Wordrap 코드 수정
		nowX = (nowX >= board.length) ? 0 : nowX;
		nowY = (nowY >= board[0].length) ? 0 : nowY;
		nowX = (nowX < 0) ? board.length - 1 : nowX;
		nowY = (nowY < 0) ? board[0].length - 1 : nowY;

		board[nowX][nowY]++;

		printBoard();
		System.out.println();
	}

	public void printBoard() {
		// Magic Number 제거
		for (int i = 0; i < board.length; i++) {
			for (int j = 0; j < board[i].length; j++) {
				System.out.print(board[i][j] + "\t");
			}
			System.out.println();
		}
	}

	public ArrayList getJouney() {
		return jouney;
	}

	public static void main(String[] args) {
		Board aboard = new Board();

		System.out.println("RandomWalk");
		aboard.board[0][0]++;

		// jouney getter로 jouney 의 참조를 얻습니다. 
		// jouney 는 aboard가 가지고 있는 것입니다.
		ArrayList jouney = aboard.getJouney();
		jouney.add("북");
		jouney.add("남동");

		// 출력부분 ArrayList 로 따른 변경
		for (int i = 0; i < jouney.size(); i++)
			aboard.move((String) jouney.get(i));
	}

}


Thread

변경중 적당한 선에서 그만 둡니다. 변화가 심하지 않은 단계를 판단해서 하나씩 바꾸어 놓았으니, IDE에 붙여서, 뭐가 바뀌었는지 보세요.

ArrayList 나, HashMap 은 보통의 자바 책들에서 나오는 Vector 와 Hashtable 과 동일한 역할을 합니다. 1.3에서 추가된 collection framework에서 위의 두가지를 더 추천해서 이용했습니다.

collection framework를 알고 싶으시면 여기 에서 보세요. 그리고 보셨으면 저에게 세미나 시켜주세요. 쿨럭.. --neocoin



Valid XHTML 1.0! Valid CSS! powered by MoniWiki
last modified 2021-02-07 05:23:31
Processing time 0.0153 sec