본문 바로가기
공부/과제.

JAVA 문제풀이 15

by 햄이; 2021. 5. 7.

 

Q1. 숫자 야구게임 함수화

package Day11;

import java.util.Random;
import java.util.Scanner;

/*
 * Q23.숫자야구게임을 함수 3개 이상으로 해서 구현을 해주세요.
 * */
public class Question1 {

	
	//컴퓨터에 랜덤값 넣는 함수
	public static int[] com() {

		Random r = new Random();
		int[] com = new int[3];

		for(int i=0; i<com.length; i++) {
			com[i] = r.nextInt(9)+1;
		}

		//랜덤값이 겹칠 시 랜덤 수 교체
		while(true){
			if(com[0] != com[1]){ 
				if(com[0] != com[2] && com[1] != com[2]){
					break;
				}else { 
					com[2] = r.nextInt(9)+1;
				}
			}else {
				com[1] = r.nextInt(9)+1;
			}
		}
		return com;
	}


	//유저에게 중복되지 않은 1~9숫자를 받는 함수
	public static int[] user() {
		Scanner sc = new Scanner(System.in);
		int user[] = new int[3];

		System.out.println("숫자 야구 게임입니다.");
		System.out.println("1~9까지의 수를 입력해주세요.");



		while(true) {
			for(int i=0; i<user.length; ) {
				user[i] = sc.nextInt();
				if(user[i]<1 || user[i]>9) {
					System.out.println("범위 내 숫자가 아닙니다. 다시 입력해주세요");
					break;
				}else if(i > 0 && user[i]==user[i-1]) {
					System.out.println("중복된 숫자입니다. 다시 입력해주세요");
					break;
				}
				i++;
			}
			if(user[0]!=user[1] && user[1]!=user[2] && user[2] !=user[0]) { 
            //숫자가 중복되지 않을 시
				break;
			}
		}
		return user;
	}


	//야구게임 실행 함수
	public static boolean game(int[] com) {

		
		int total = 0;
		boolean result = false;


		System.out.print("컴퓨터의 숫자 : ");
		for(int i=0; i<com.length; i++) {
			System.out.print(com[i]+" ");
		}

		while(true) {
			int ball = 0;
			int strike =0;	
			int [] user = user();
			total++;
			
			for(int i=0; i<3; i++) {
				for(int j=0; j<3; j++) {
					if(user[i] == com[j]) {
						if(i==j) {
							strike++;
						}else {
							ball++;
						}
					}

				}
			}

			if(ball!=0 || strike !=0) {
				if(strike ==3) { // strike가 3개일 때 = 홈런, 프로그램 종료
					System.out.println("홈런입니다.");
					System.out.print("컴퓨터의 숫자 : ");
					for(int i=0; i<com.length; i++) {
						System.out.print(com[i]+" ");
					}
					System.out.println();
					System.out.println("총 게임 시도 횟수 : "+total+"회");
					System.out.println("프로그램을 종료합니다.");
					result = true;
					break;
				}else {
					System.out.println("이번 게임의 결과는 "+ball+"볼 "+strike+"스트라이크 입니다.");
				}
			}
		}
		
		return result;

	}



	public static void main(String[] args) {
		// TODO Auto-generated method stub

		
		int[] com = com();
		while(true) {
			boolean result = game(com);
			if(result == true)
				break;
			}
		}
		
}	

 

 

Q2. 랜덤 범인찾기 게임 함수화

package Day11;

import java.util.Random;
import java.util.Scanner;

/*
 * Q.24
 * 랜덤으로 1~5까지 받고 1~5번 중 선택 된 번호는 범인입니다.
 * 유저는 1~5까지 입력을 하여서 범인을 찾는 게임을 만들어주세요
 * 범인을 찾을 때까지 계속 반복해주세요
 * 범인 번호가 아닌 값을 입력하면 "범인을 잡지 못했습니다."출력
 * 범인번호를 입력하면 "범인을 잡았습니다" 출력후에 프로그램을 종료합니다.
 * 함수는 3개로 만들어주시고
 * 단, 1번과 3번만을 사용해서 만들어주세요.
 * 주고받고와 / 주고 안받고
 * */
public class Question2 {

	//랜덤으로 범인생성
	public static int thief() {
		Random r = new Random();
		int thief = r.nextInt(5)+1;
		System.out.println("테스트용 범인의 숫자 : "+ thief);
		return thief;
	}


	public static int user() {
		int user = 0;
		
		while(true) {
			Scanner sc = new Scanner(System.in);
			System.out.println("1~5까지의 숫자를 입력하여 범인을 찾아주세요");
			user = sc.nextInt();
			
			if(user>=1 && user<=5) {
				break;
			}else {
				System.out.println("잘못된 숫자입니다.");
			}
		}
		return user;
	}


	public static boolean find(int user,int thief) {
		
		boolean result = false ;
		if(user == thief) {
			result = true;
		}
		return result;
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		int thief = thief();
		
		while(true) {
			int user = user();
			boolean result = find(user, thief);
			if(result == true) {
				System.out.println("축하합니다 범인을 찾았습니다.");
				break;
			}else {
				System.out.println("범인 색출에 실패했습니다.");
			}
		}
		
	}

}

 

 

위 실행 결과

 

Q3. 낚시게임 함수화

package Day11;

import java.util.Random;
import java.util.Scanner;

/*
 * Q.25
 * 낚시게임을 함수화 진행해주세요
 * 함수는 총 5개를 만듭니다
 * 3번형식 물고기 랜덤값 생성 // 주고 안받고
 * 3번 형식 캐스팅 //주고 안받고
 * 2번형식 물고기가 있는 위치 출력함수 // 안주고 받고
 * 1번형식 낚시대 이동함수 // 인데 3번형식으로 풀었음
 * 4번형식 물고기 있는 체크함수 
 * */
public class FishGame {

	//3번 형식 물고기 랜덤값 생성
	public static int[][] fish() {

		Random r = new Random();
		int[][] place = new int[5][5];

		int row = 0;
		int col = 0;

		//물고기 세 마리 랜덤으로 넣어주기
		for(int i=0; i<3; i++) {
			row = r.nextInt(5);
			col = r.nextInt(5);
			if(place[row][col]==0) {
				place[row][col] = 1; //비어있는 자리일 때 1(물고기) 입력
			}else {
				i--;
			}
		}
		return place;
	}
	
	// 3번 형식 캐스팅 
	public static int[] casting() {
		
		Scanner sc = new Scanner(System.in);
		System.out.println("캐스팅을 시작하겠습니다.");
		int x = 0;
		int y = 0;
		int[] casting = new int[2];
		
		while(true) {
			System.out.println("X좌표를 입력해주세요");
			x = sc.nextInt();
			System.out.println("Y좌표를 입력해주세요");
			y = sc.nextInt();
			
			if(x>=0 && x<5 && y>=0 && y<5) {
				casting[0] = x;
				casting[1] = y;
				break;
			}else {
				System.out.println("좌표값이 정확하지 않습니다. 다시 입력해주세요.");
			}
		}
		return casting;
	}
	
	
	
	
	//2번 형식 물고기 위치 출력 함수
	public static void fishplace(int[][] place) {
		System.out.println("물고기의 위치");
		for(int i=0; i<place.length; i++) {
			for(int j=0; j<place.length; j++) {
				if(place[i][j]!=0) 
					System.out.println(+i+" "+j+" ");
			}
		}
	}
	
	//4번 형식 낚시대 이동함수 but,문제가 안풀려서 3번형식으로 변경
	public static int moving() {
	
		Scanner sc = new Scanner(System.in);
		int moving = 0;
		
		while(true) {
			System.out.println("낚시대를 어디로 이동하시겠습니까");
			System.out.println("1. 위  | 2. 아래 | 3. 왼쪽 | 4. 오른쪽 ");
			moving = sc.nextInt();

			if(moving>=1 && moving<=4) {
				break;
			}else {
				System.out.println("잘못된 캐스팅입니다.");
				System.out.println();
			}
		}
		return moving;
	}
	
	//4번 형식 물고기 있는지 체크하는 함수
	public static void fishcheck() {
		int[][] place = fish(); //1) 랜덤 물고기 생성
		fishplace(place);//2) 테스트를 하기 위한 물고기 위치 출력
		
		int[] casting = casting(); // 3) 첫 캐스팅
		int x = casting[0];//x좌표
		int y = casting[1];//y좌표
		
		int fish = 0;//잡은 물고기 수 
		boolean move = false;
		
		//4)첫 캐스팅에서 물고기가 있는지 확인
		if(place[x][y]==1) {
			System.out.println("물고기 1마리를 잡았습니다.");
			place[x][y]=0;
			fish++;
		}else {
			System.out.println("물고기가 없습니다.");
		}
		
		
		while(fish<3) {//5)물고기가 3마리 미만일 때만 반복동작
			
			int moving = moving(); // 6) 낚시대 이동 함수
			
			switch(moving) { //위 아래 왼쪽 오른쪽
			case 1 : { //위
				y--;
				if(y<0 || y>4) {
					System.out.println("더이상 이동할 수 없습니다.");
					y++;
				}
				move = true; //올바른 동작일 때 move를 true로 바꿔줌
				System.out.println("현재 좌표"+x+" "+y);
				break;
			}
			case 2 :{ // 아래
				y++;
				if(y<0 || y>4) {
					System.out.println("더이상 이동할 수 없습니다.");
					y--;
				}
				move = true;
				System.out.println("현재 좌표"+x+" "+y);
				break;
			}case 3 :{ // 왼쪽
				x--;
				if(x<0 || x>4) {
					System.out.println("더이상 이동할 수 없습니다.");
					x++;
				}
				move = true;
				System.out.println("현재 좌표"+x+" "+y);
				break;

			}case 4 :{ // 오른쪽
				x++;
				if(x<0 || x>4) {
					System.out.println("더 이상 이동할 수 없습니다.");
					x--;
				}
				move = true;
				System.out.println("현재 좌표"+x+" "+y);
				break;
			}
			}
			
			
			if(move == true) {//올바른 동작일 때
				if(place[x][y]!=0) { //그 좌표에 0이 아닌 수가 들어있을 시
					System.out.println("물고기 1마리를 잡았습니다.");
					place[x][y]=0;
					fish++; // 잡은 물고기 수 증가
					System.out.println("현재 물고기 수 :"+fish);
					if(fish==3) { 
						System.out.println("축하합니다 물고기 3마리를 모두 잡았습니다.");
					}
				}
			}
		}
		
	}
	
	
	
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		fishcheck();
	}

}

 

 

Q4. Q3의 가위바위보 문제 함수화

package Day11;
/
*Q26. Q3가위바위보 문제 함수화
*
*/
import java.util.Random;
import java.util.Scanner;

public class Question3 {

		// TODO Auto-generated method stub
		public static int comRan()
		{
			Random r = new Random();
			return r.nextInt(3);
		}
		
		public static String userInput()
		{
			Scanner sc = new Scanner(System.in);
			System.out.println("가위 바위 보를 입력 : ");
			return sc.next();
			
		}
		
		public static int changeUserValue(String str)
		{
			int user;
			if(!(str.equals("가위") ||str.equals("바위") || str.equals("보")))
			{
				System.out.println("잘못된입력입니다.");
				return -1;
			}
			else
			{
				//equals("가위") => 함수 String안에 있는 함수 int 기본형 함수 자체가 없습니다.
				if(str.equals("가위"))
				{
					user = 0;
				}
				else if(str.equals("바위"))
				{
					user = 1;
				}
				else
				{
					user = 2;
				}
			}
			
			return user;
		}
		
		
		public static void check(int user, int ran)
		{
			
			if(user != -1)
			{
				int value = user - ran ;
				
				if(value == 1 || value == -2)
				{
					System.out.println("유저승");
				}
				else
				{
					if(value == 0)
					{
						System.out.println("무승부");
					}
					else
					{
						System.out.println("컴퓨터 승");
					}
				}
			}
		
		}
			
		public static void main(String[] args) {
			check(changeUserValue(userInput()), comRan());
		
		}

}

위 실행 결과

 

1번과 3번은

최근 올렸던 문제를

함수화하는 문제였기에

실행 결과는 스킵!

'공부 > 과제.' 카테고리의 다른 글

JAVA 문제풀이 17  (0) 2021.07.02
JAVA 문제풀이 16  (0) 2021.05.07
JAVA 문제풀이 14  (0) 2021.05.07
JAVA 문제풀이 13 배열 낚시 게임  (0) 2021.04.28
JAVA 문제풀이 12 버블정렬  (0) 2021.04.26

댓글