Java
자바 메소드 (Method) 를 사용해 숫자야구 만들기
연수
2020. 7. 21. 14:27
package Fifthprogram; import java.util.Random; import java.util.Scanner; public class practice4 { static int[] input_1() // 함수명 input_1 주고 받지 않는 함수 { Random r = new Random(); int com[] = new int[3]; // 1차 배열 com[0]=r.nextInt(9)+1; // 첫번째 자리에 랜덤 수 1~9 중 투입 com[1]=r.nextInt(9)+1; // 두번째 자리에 랜덤 수 1~9 중 투입 if(com[0]==com[1]) // 첫번째 자리의 랜덤 수와 두번째 자리의 랜덤 수가 같다면 { com[1]=r.nextInt(9)+1; // 다시 랜덤 수를 출력 } com[2]=r.nextInt(9)+1; if(com[0]==com[2] || com[1]==com[2]) // 첫번째 자리의 랜덤 수와 세번째 자리의 랜덤 수가 같다면 또는 두번째 자리의 랜덤 수와 세번째 자리의 랜덤 수가 같다면 { com[2]=r.nextInt(9)+1; // 다시 랜덤 수를 출력 } for(int i=0; i<3; i++) {System.out.println(com[i]);} // 컴퓨터가 임의로 정한 숫자 세개 출력 return com; // 메인 함수에 컴퓨터 랜덤 값을 리턴 } static int[] input_2() // 함수명 input_2 주고 받지 않는 함수 { Scanner sc = new Scanner(System.in); int user[] = new int[3]; // 1차 배열 while (true) { for(int i=0; i<3; i++) { System.out.print((i+1)+"번째 숫자를 입력하세요: "); // 유저값 출력 user[i] = sc.nextInt(); } if(user[0]==user[1] || user[1]==user[2] || user[0]==user[2]) { System.out.println("중복된 숫자를 입력하셨습니다."); continue; // 중복된 숫자 입력시 다시 전 단계로 돌아감 } else { break; // 중복되지 않은 숫자 세개 입력 시 반복문 탈출 } } return user; // 유저 값 리턴 } static int []result_1 (int com[], int user[]) { int strike=0; int ball=0; int[]temp = new int[2]; // Strike, Ball 두개 값을 받아야해서 배열이 필요함 for(int i=0; i<3; i++) { for(int j=0; j<3; j++) {if(com[i]==user[j]) if(i==j) // ex) com[0]=user[0]이면 같은 0번째 자리에 똑같은 수가 있으므로 스트라이크 { strike++; } else // ex) com[0]=user[1]이면 컴퓨터 0번째 자리와 유저 첫번째 자리에 똑같은 수가 있으므로 볼 { ball++; } } } temp[0]=strike; temp[1]=ball; // 임의로 스트라이크와 볼의 자리를 정해줌 return temp; // temp 값 리턴 } static boolean result_2 (int temp[]) // 함수명 return_2, 정수 temp[]를 받으며 주는 함수 { if(temp[0]==3) { System.out.println("홈런입니다."); return true; } else if (temp[0]==0 && temp[1]==0) { System.out.println("아웃입니다."); return false; } else { System.out.println("Strike: " + temp[0] + "Ball: " + temp[1] + "입니다."); return false; } } public static void main(String[] args) { // TODO Auto-generated method stub int com[]; int user[]; int temp[]; com = input_1(); while(true) { user=input_2(); temp=result_1(com, user); if(result_2(temp)) {break;} } } }