🔥 Vamos/Java

1001 | 조건, 반복문으로 가위바위보 게임 만들기

unikue 2022. 10. 1. 18:48

자바의 정석 예제 4-7 약간 변형.

 

👉 원랜 당신은 1, 컴퓨터가 2 라는 식으로 숫자가 출력되는데 가위/바위로 명시하고 싶어서 조금 추가를 했다.

public static void main(String[] args) {
		System.out.println("가위(1), 바위 (2), 보(3)중 하나를 입력하세요 : ");
		
		Scanner scanner = new Scanner(System.in);
		int user = scanner.nextInt();
		int com = (int)(Math.random()*3+1);
		
		if (user==1) {
			System.out.println("당신은 가위를 냈습니다.");
		}
		else if(user==2) {
			System.out.println("당신은 바위를 냈습니다.");
		}
		else {
			System.out.println("당신은 보를 냈습니다.");
		} 

		if (com==1) {
			System.out.println("컴퓨터는 가위를 냈습니다.");
		}
		else if(com==2) {
			System.out.println("컴퓨터는 바위를 냈습니다.");
		}
		else {
			System.out.println("컴퓨터는 보를 냈습니다.");
		} 
		
		switch(user-com) {
		case -2: case 1:
			System.out.println("당신이 이겼습니다.");
		break;
		
		case 0:
			System.out.println("비겼습니다.");
		break;
		
		case 2 : case -1:
			System.out.println("당신이 졌습니다.");
		break;	
		}	
						
		} //end of main

 

 

 

👉 여기서 가위바위보를 이길때까지 해보고 싶은데, 돌아가는 방법이 뭐였더라 하다가 뒷부분 복습하며 다시 생각남. 이름 지정해서 continue를 쓸수가있었지....... 그새까먹었다니................여튼 추가함!

 

 

	public static void main(String[] args) {
		
		System.out.println("가위(1), 바위 (2), 보(3)중 하나를 입력하세요 : ");
		
		repeat: while(true) {	// 무한반복문 생성. 대신 아래에서 조건에따라 탈출할수 있게 설정.
			Scanner scanner = new Scanner(System.in);
			int user = scanner.nextInt();
			int com = (int)(Math.random()*3+1); //계속 랜덤생성되어야 하므로 while문 안에 들어가게함
		
		if (user==1) {
			System.out.println("당신은 가위를 냈습니다.");
		}
		else if(user==2) {
			System.out.println("당신은 바위를 냈습니다.");
		}
		else {
			System.out.println("당신은 보를 냈습니다.");
		} 

		if (com==1) {
			System.out.println("컴퓨터는 가위를 냈습니다.");
		}
		else if(com==2) {
			System.out.println("컴퓨터는 바위를 냈습니다.");
		}
		else {
			System.out.println("컴퓨터는 보를 냈습니다.");
		} 
		
		switch(user-com) {
		case -2: case 1:
			System.out.println("당신이 이겼습니다.");
		break repeat;	// 프로그램 종료
		
		case 0:
			System.out.println("비겼습니다.");
			System.out.println("가위(1), 바위 (2), 보(3)중 하나를 입력하세요 : "); // 재도전문구
		continue repeat;
		
		case 2 : case -1:
			System.out.println("당신이 졌습니다.");
			System.out.println("가위(1), 바위 (2), 보(3)중 하나를 입력하세요 : ");	// 재도전문구
		continue repeat;
			} // end of switch
		}	// end of while			
		} //end of main

 


책보고 똑같이 입력해도 안풀리는 문제랑 전에 했던건데도 기억이 안나고&고민해도 안풀리는게 있어서 오늘 공부 김새고 있었는데 그나마 하나는 생각한대로 바꿔낼 수 있어서 다행이다..... 정신맑을때 못한건 다시봐야지 ㅠㅠ