코딩도장

숫자야구

0~9까지의 숫자를 한 번씩 사용하여 만든 세 자리 숫자를 맞추는 코드를 작성하시오. 숫자와 자리가 맞으면 S이고 숫자만 맞으면 B입니다.

컴퓨터가 세 자리 숫자를 설정하고 사용자에게 숫자를 입력받아 S와 B의 개수를 알려주십시오. 정답을 맞히면 정답이라고 알려주고 사용자가 숫자를 룰에 어긋나게 입력 시 경고문을 출력하고 다시 숫자를 입력할 수 있게 하십시오.

예) 정답이 123일 때 사용자가 234를 입력 시 0S2B, 사용자가 109를 입력 시 1S0B, 사용자가 327을 입력 시 1S1B입니다.

random

2022年07月15日 13:59

Tae Joo

(追記) (追記ここまで)
댓글 작성은 로그인이 필요합니다.
(注記) 상대에게 상처를 주기보다 서로에게 도움이 될 수 있는 댓글을 달아 주세요.

8개의 풀이가 있습니다.


import java.util.Random; // 임의의 수를 입력하기 위한 랜덤 임포트
import java.util.Scanner; // 플레이어 입력을 위한 스캐너 임포트
public class NumGame { // 클래스 이름은 게임명
 public static void main(String[] args) { // 메인메서드 시작
 Random r = new Random(); // 랜덤메서드 객체 선언
 Scanner sc = new Scanner(System.in); // 스캐너메서드 객체 선언
 int[] rnums = new int[3]; // 랜덤숫자를 담을 배열 선언
 int[] input_nums = { 0, 0, 0 }; // 플레이어 입력 변수를 담을 배열 선언 및 초기화
 int times = 0; // 플레이어 문제풀이 횟수를 담을 변수 선언
 System.out.println("Line13");
 rnums[0] = r.nextInt(1, 9); // 랜덤숫자를 담을 변수 중 첫번째는 바로 입력
 System.out.println(rnums[0]);
 boolean num123 = (rnums[0] == rnums[1]) || (rnums[0] == rnums[2]) || (rnums[1] == rnums[2]);
 // 랜덤숫자가 서로 같은 게 하나라도 있을 경우에 따른 boolean값을 담을 변수
 while (true) { // 위 boolean값을 담은 값
 rnums[1] = r.nextInt(1, 9); // 두번째 숫자에 랜덤숫자를 다시 대입
 rnums[2] = r.nextInt(1, 9); // 세번째 숫자에 랜덤숫자를 다시 대입
 if ((rnums[0] == rnums[1]) || (rnums[0] == rnums[2]) || (rnums[1] == rnums[2])) {
 continue;
 } else {
 break;
 }
 }
 System.out.println(rnums[1]);
 System.out.println(rnums[2]);
 System.out.println("Line21");
 while (rnums[0] != input_nums[0] || rnums[1] != input_nums[1] || rnums[2] != input_nums[2]) {
 // 랜덤숫자와 플레이어 입력 숫자가 하나라도 틀리면 while문 진입함.
 // 반대로, 모두 같으면(정답이면) while문 진입하지 않음.
 int strike = 0; // 게임기능 스트라이크를 담을 변수 선언 및 초기화
 int ball = 0; // 게임기능 볼을 담을 변수 선언 및 초기화
 try {
 System.out.print("숫자 >> "); // 입력 안내메시지
 input_nums[0] = sc.nextInt(); // 첫번째자리 입력
 input_nums[1] = sc.nextInt(); // 두번째자리 입력
 input_nums[2] = sc.nextInt(); // 세번째자리 입력
 boolean ip0 = (input_nums[0] >= 10) || (input_nums[0] <= 0);
 boolean ip1 = (input_nums[1] >= 10) || (input_nums[1] <= 0);
 boolean ip2 = (input_nums[2] >= 10) || (input_nums[2] <= 0);
 if (ip0 || ip1 || ip2) {
 continue;
 }
 } catch (Exception e) {
 System.err.println("잘못된 입력입니다. 다시 입력해주시기 바랍니다.");
 continue;
 }
 times++; // 시도횟수 증감식. 제대로 입력했을 경우에만 증가하도록 함.
 for (int i = 0; i < input_nums.length; i++) {
 if (rnums[i] == input_nums[i]) {
 strike += 1;
 } else {
 if (i == 0) {
 if (rnums[0] == input_nums[1] || rnums[0] == input_nums[2]) {
 ball += 1;
 }
 } else if (i == 1) {
 if (rnums[1] == input_nums[0] || rnums[1] == input_nums[2]) {
 ball += 1;
 }
 } else if (i == 2) {
 if (rnums[2] == input_nums[1] || rnums[2] == input_nums[0]) {
 ball += 1;
 }
 }
 }
 }
 System.out.printf("%dS %dB\n", strike, ball);
 // 게임결과 출력
 System.out.println();
 // 가독성을 위한 줄바꿈
 }
 System.out.printf("축하합니다! %d번만에 문제를 맞혔습니다.", times);
 }
}
댓글 작성은 로그인이 필요합니다.
(注記) 상대에게 상처를 주기보다 서로에게 도움이 될 수 있는 댓글을 달아 주세요.

자바로 작성하였습니다.

package baseball;
import java.util.Scanner;
public class main {
 public static void main(String[] args) {
 Scanner sc = new Scanner(System.in);
 int base1 = (int) (Math.random() * 9 + 1);
 int base2 = (int) (Math.random() * 9 + 1);
 int base3 = (int) (Math.random() * 9 + 1);
 //이상 123은 정답 숫자
 int s = 0;
 int b = 0;
 int homerun = 0;
 int out = 0;
 //3가지 숫자가 겹치지 않게금 해주는 코드
 while (true) {
 while (base1 == base2) {
 base2 = (int) (Math.random() * 9 + 1);
 if (base1 != base2) {
 }
 }
 while (base3 == base1 & base3 == base2) {
 base3 = (int) (Math.random() * 9 + 1);
 if (base3 != base1 & base3 != base2) {
 }
 }
 if (base1 != base2 & base1 != base3 & base2 != base3) {
 break;
 }
 }
 //코드 끝
 exit: while (true) {
 while (out != 3) {
 System.out.println("------------");
 System.out.println("당신의 카운트" + out);
 System.out.println("3이되면 패배합니다.");
 System.out.println("------------");
 System.out.println("첫번째 숫자를 입력하십시오");
 int run1 = sc.nextInt();
 System.out.println("두번째 숫자를 입력하십시오");
 int run2 = sc.nextInt();
 System.out.println("세번째 숫자를 입력하십시오");
 int run3 = sc.nextInt();
 //이상 유저의 입력을 받는 숫자.
 if (run1 == base1) {
 s = s + 1;
 }
 if (run1 == base2) {
 b = b + 1;
 }
 if (run1 == base3) {
 b = b + 1;
 }
 if (run2 == base1) {
 b = b + 1;
 }
 if (run2 == base2) {
 s = s + 1;
 }
 if (run2 == base3) {
 b = b + 1;
 }
 if (run3 == base1) {
 b = b + 1;
 }
 if (run3 == base2) {
 b = b + 1;
 }
 if (run3 == base3) {
 s = s + 1;
 }
 if (s == 3) {
 System.out.println("홈런");
 homerun = homerun + 1;
 }
 if (s == 0 & b == 0) {
 System.out.println("아웃");
 out = out + 1;
 } else if (s != 3) {
 System.out.println("스트라이크: " + s);
 System.out.println("볼: " + b);
 }
 s = 0;
 b = 0;
 if (homerun == 1 | out == 3) {
 System.out.println("게임종료");
 if (homerun == 1) {
 System.out.println("승리하였습니다.");
 break exit;
 } else if (out == 3) {
 System.out.println("패배하였습니다.");
 break exit;
 }
 }
 }
 }
 }
}
댓글 작성은 로그인이 필요합니다.
(注記) 상대에게 상처를 주기보다 서로에게 도움이 될 수 있는 댓글을 달아 주세요.
import java.util.Random;
import java.util.Scanner;
import java.util.stream.IntStream;
public class CountBaseBall {
 public static final int DIGIT_NUM = 5; // 숫자야구게임 문제&정답숫자 자릿수
 private static String[] digitStr = new String[DIGIT_NUM]; // 정답숫자 
 private static String[] inputStr = new String[DIGIT_NUM]; // 입력숫자
 private static Scanner sc; // 입력객체
 public static void main(String[] args) {
 int[] num = { 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 }; // int형 배열
 Random r = new Random();
 String bf = null;
 for (int i = 0; i < digitStr.length; i++) {
 int idx = r.nextInt(num.length);
 digitStr[i] = num[idx] + "";
 num = remove(num, idx);
 }
 System.out.println(":::::::::::::::::::: BaseBall Game Start ::::::::::::::::::::");
 try {
 sc = new Scanner(System.in);
 while (true) {
 System.out.print("[0-9까지] 서로다른 "+DIGIT_NUM+"자리의 값을 입력하시오 : ");
 bf = sc.nextLine();
 if (bf != null && bf.length() == DIGIT_NUM) {
 boolean isNumeric = bf.matches("[+-]?\\d*(\\.\\d+)?"); // 입력된 값 숫자여부 판단
 if (isNumeric && dupCheck(bf)) {
 bf = bf.substring(0, DIGIT_NUM);
 System.out.println("입력한 답 : " + bf);
 inputStr = bf.split("");
 } else {
 // 숫자로 다시입력
 continue;
 }
 int strike = 0;
 int ball = 0;
 for (int j = 0; j < digitStr.length; j++) {
 for (int k = 0; k < inputStr.length; k++) {
 if (digitStr[j].equals(inputStr[k])) {
 if (j == k) {
 strike++;
 } else {
 ball++;
 }
 }
 }
 }
 if (strike == digitStr.length) {
 System.out.println("정답입니다!! 축하합니다!");
 System.out.println(":::::::::::::::::::: BaseBall Game End ::::::::::::::::::::");
 break;
 } else {
 System.out.println("아쉽습니다.. [ " + strike + "S" + ball + "B ] 입니다");
 }
 }
 } 
 } catch (Exception e) {
 // 예외처리
 }
 }
 private static boolean dupCheck(String bf) {
 String[] str = bf.split("");
 for (int i = 0; i < str.length; i++) {
 for (int j = (i+1); j < str.length; j++) {
 if ( str[i].equals(str[j])) {
 return false;
 }
 }
 }
 return true;
 }
 /**
 * 숫자야구게임에서 중복된 숫자를 허용하지 않도록 idx 값 사용 후 제거하는 기능
 * @param num int형 숫자배열
 * @param idx 삭제할 index 값
 * @return 필터링 된 num 값
 */
 private static int[] remove(int[] num, int idx) {
 return IntStream.range(0, num.length)
 .filter(i -> i != idx)
 .map(i -> num[i])
 .toArray();
 }
}
댓글 작성은 로그인이 필요합니다.
(注記) 상대에게 상처를 주기보다 서로에게 도움이 될 수 있는 댓글을 달아 주세요.
import java.util.HashSet;
import java.util.Scanner;
public class CD_baseball {
 public static void main(String[] args) {
 Scanner sc = new Scanner(System.in);
 int a;
 int b;
 int c;
 int ball;
 int strike;
 while(true) {
 a = (int)(Math.random()*10);
 b = (int)(Math.random()*10);
 c = (int)(Math.random()*10);
 HashSet<Integer> p = new HashSet<Integer>();
 p.add(a);
 p.add(b);
 p.add(c);
 if(p.size()==3) {
 break;
 }
 }
 System.out.println(a*100+b*10+c);
 while(true) {
 strike = 0;
 ball = 0;
 System.out.println("1번 숫자 입력");
 int s_a = sc.nextInt();
 System.out.println("2번 숫자 입력");
 int s_b = sc.nextInt();
 System.out.println("3번 숫자 입력");
 int s_c = sc.nextInt();
 if(s_a==a||s_a==b||s_a==c) {
 if(s_a==a) {
 strike++;
 }else {ball++;
 }
 } 
 if(s_b==a||s_b==b||s_b==c) {
 if(s_b==b) {
 strike++;
 }else {ball++;
 }
 } 
 if(s_c==a||s_c==b||s_c==c) {
 if(s_c==c) {
 strike++;
 }else {ball++;
 }
 } 
 System.out.println(strike+"스트라이크,"+ball+"볼");
 if(s_a==a&&s_b==b&&s_c==c) {
 System.out.println("축하합니다 다 맞추었습니다.");
 break;
 }
 }
 sc.close();
 }
}

2022年08月30日 17:16

YR L

댓글 작성은 로그인이 필요합니다.
(注記) 상대에게 상처를 주기보다 서로에게 도움이 될 수 있는 댓글을 달아 주세요.
import java.util.Scanner;
public class Q1 {
 static public String hunanswer = new Scanner(System.in).next();
 static public char[] hun = hunanswer.toCharArray();
 static public void main(String args[]) {
 int j=0,S=0,B=0;
 String input = new Scanner(System.in).next();
 while(j!=3){
 char c = input.charAt(j);
 if(c==hun[j]) {
 S++;
 j++;
 }
 else {
 if(c==hun[0]) {
 B++;
 j++;
 }
 else if(c==hun[1]) {
 B++;
 j++;
 }
 else if(c==hun[2]) {
 B++;
 j++;
 }
 else {
 j++;
 }
 }
 }
 System.out.printf("%dS%dB\n",S,B);
 if(S==3) {
 System.out.printf("정답\n");
 }
 else {
 System.out.println("틀렸습니다.\n");
 main(args);
 }
 }
}

2022年09月20日 15:10

김민중

댓글 작성은 로그인이 필요합니다.
(注記) 상대에게 상처를 주기보다 서로에게 도움이 될 수 있는 댓글을 달아 주세요.

print("!!!숫자야구 게임!!!")
import random
import sys
a = random.randint(0,9)
b = random.randint(0,9)
c = random.randint(0,9)
while True:
 if a == b:
 b = random.randint(0,9)
 if b == c:
 c = random.randint(0,9)
 if a == c:
 c = random.randint(0,9)
 if a != b and b != c and c != a:
 break
while True:
 n = input("세자리 숫자: ")
 if not n.isdigit() or len(n) != 3:
 print("잘못된 입력입니다. 세자리 숫자를 입력해주세요.")
 continue
 x = int(n[0])
 y = int(n[1])
 z = int(n[2])
 s = ball = 0
 if a == x:
 s += 1
 elif a == y or a == z:
 ball += 1
 if b == y: 
 s += 1
 elif b == x or b == z:
 ball += 1
 if c == z:
 s += 1
 elif c == x or c == y:
 ball += 1
 if s == 3:
 print("정답!!!")
 sys.exit()
 else:
 print(f"{s}S{ball}B 입니다")
 continue
```{.java}
java
import java.util.Random;
import java.util.Scanner;
public class numberBassballGame 
{
 public static void main(String[] args) 
 {
 Random random = new Random();
 int random_num1 = 0; //컴퓨터가 생성하는 랜덤값(정답)
 int random_num2 = 0; //컴퓨터가 생성하는 랜덤값(정답)
 int random_num3 = 0; //컴퓨터가 생성하는 랜덤값(정답)
 int first = 0; //user 입력값의 백의자리
 int second = 0; //user 입력값의 십의자리
 int third = 0; //user 입력값의 일의자리
 random_num1 = random.nextInt(9); //0~9
 random_num2 = random.nextInt(9); //0~9
 random_num3 = random.nextInt(9); //0~9
 Scanner scanner = new Scanner(System.in);
 while (true)
 {
 if (random_num1 == random_num2)
 {
 random_num2 = random.nextInt(9);
 }
 if (random_num2 == random_num3)
 {
 random_num3 = random.nextInt(9);
 }
 if (random_num1 == random_num3)
 {
 random_num3 = random.nextInt(9);
 }
 if (random_num1 != random_num2 && random_num2 != random_num3 && random_num3 != random_num1)
 {
 break;
 }
 }
 while (true)
 {
 System.out.printf("백의자리 숫자를 입력해주세요");
 first = scanner.nextInt();
 System.out.printf("십의자리 숫자를 입력해주세요");
 second = scanner.nextInt();
 System.out.printf("일의자리 숫자를 입력해주세요");
 third = scanner.nextInt();
 int strike = 0;
 int ball = 0;
 if (first == second)
 {
 System.out.printf("서로다른 숫자를 입력해주세요");
 continue;
 }
 if (second == third)
 {
 System.out.printf("서로다른 숫자를 입력해주세요");
 continue;
 }
 if (first == third)
 {
 System.out.printf("서로다른 숫자를 입력해주세요");
 continue;
 }
 if (random_num1 == first)
 {
 strike += 1;
 }
 else if (random_num1 == second || random_num1 == third)
 {
 ball += 1;
 }
 if (random_num2 == second)
 {
 strike += 1;
 }
 else if (random_num2 == first || random_num2 == third)
 {
 ball += 1;
 }
 if (random_num3 == third)
 {
 strike += 1;
 }
 else if (random_num3 == first || random_num3 == second)
 {
 ball += 1;
 }
 System.out.printf("strike: %d, ball: %d%n", strike, ball);
 if (strike == 3) 
 {
 System.out.printf("정답!!!");
 break;
 }
 else 
 {
 continue;
 }
 }
 }
 }
댓글 작성은 로그인이 필요합니다.
(注記) 상대에게 상처를 주기보다 서로에게 도움이 될 수 있는 댓글을 달아 주세요.
package main;
import java.util.Arrays;
import java.util.Scanner;
public class NumberBaseball { // 최종 결과 출력
 public static void main(String[] args) {
 String a[];
 a = ComPare.comPa();
 System.out.println("유저 숫자 : " + a[0]);
 System.out.println("컴퓨터 숫자 : " + a[1]);
 System.out.println("결과 : " + a[2]);
 }
}
class UserNumberScan { // 유저 번호 적기
 static int[] userNum() {
 int userNumber[];
 userNumber = new int[3];
 Scanner UserScan = new Scanner(System.in);
 for (int i = 0; i < 3; i++) {
 int num = UserScan.nextInt() ;
 userNumber[i] = num;
 if(num < 0 || num > 10){ // 1~9 사이 체크
 System.out.println("1~9 사이로 다시 입력하세요");
 i--;
 }
 else { //중복 번호 확인
 for (int e = 0; e < 3; e++) {
 if (e != i && userNumber[i] == userNumber[e]) {
 System.out.println("중복된 값입니다.");
 i--;
 break;
 }
 }
 }
 }
 UserScan.close();
 return userNumber;
 }
}
class ComNum { //컴퓨터 번호 출력
 static int[] comNu() {
 int ComNu[];
 ComNu = new int[3];
 for (int i = 0; i < 3; i++) {
 int random = (int) (Math.random() * 8) + 1;
 ComNu[i] = random;
 for (int e = 0; e < 3; e++) {
 if (e != i && ComNu[i] == ComNu[e]) { //중복 번호 확인
 i--;
 }
 }
 }
 return ComNu;
 }
}
class ComPare { // 유저와 컴퓨터 비교
 public static String[] comPa() {
 int ComNu[];
 int UserSc[];
 ComNu = ComNum.comNu();
 UserSc = UserNumberScan.userNum();
 int Strike = 0;
 int Ball = 0;
 for (int i = 0; i < 3; i++) { //유저 숫자 위치
 for (int e = 0; e < 3; e++) { //컴퓨터 숫자 위치
 if(i == e && UserSc[i] == ComNu[e]){ //스트라이크 비교
 Strike++;
 break;
 }
 else if(UserSc[i] == ComNu[e]){ //볼 비교
 Ball++;
 break;
 }
 }
 }
 String[] Result = new String[3]; //int 배열을 string 배열로 변경 후 리턴
 Result[0] = Arrays.toString(UserSc);
 Result[1] = Arrays.toString(ComNu);
 Result[2] = Strike + "S" + Ball + "B";
 return Result;
 }
}

2022年11月23日 12:39

Gi Lick

댓글 작성은 로그인이 필요합니다.
(注記) 상대에게 상처를 주기보다 서로에게 도움이 될 수 있는 댓글을 달아 주세요.
package 숫자야구;
import java.util.Scanner;
public class NumberBaseball { //메인 클래스
 public static void main(String[] args) {
 // TODO Auto-generated method stub
 Scanner scanner = new Scanner(System.in);
 NumberGenerator ng = new NumberGenerator();
 NumberCount nc = new NumberCount();
 String answer = ng.getNum();
 while(true) {
 System.out.println("숫자를 입력하세요.");
 String guess = scanner.next();
 int[] score = nc.count(guess, answer);
 System.out.println("S: " + score[0] + ", B: " + score[1]);
 if(score[0] == 3) {
 System.out.println("정답!");
 break;
 }
 }
 }
}
package 숫자야구;
public class NumberCount {
 int[] count(String number, String answer) {
 int strike = 0;
 int ball = 0;
 char[] numberArray = number.toCharArray();
 char[] answerArray = answer.toCharArray();
 for (int i = 0; i < numberArray.length; i++) {
 for (int j = 0; j < answerArray.length; j++) {
 if(numberArray[i] == answerArray[j]) {
 if(i == j) {
 strike += 1;
 }
 else {
 ball += 1;
 }
 }
 }
 }
 return new int[] {strike, ball};
 }
}
package 숫자야구;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class NumberGenerator {
 String getNum() {
 String num = "";
 List<String> numbers = new ArrayList<String>();
 for (int i = 0; i < 10; i++) {
 numbers.add(String.valueOf(i));
 }
 Random random = new Random();
 for (int i = 0; i < 3; i++) {
 int rand = random.nextInt(numbers.size());
 num = num + numbers.get(rand);
 numbers.remove(rand);
 }
 return num;
 }
}

2025年01月07日 21:54

박준우

댓글 작성은 로그인이 필요합니다.
(注記) 상대에게 상처를 주기보다 서로에게 도움이 될 수 있는 댓글을 달아 주세요.

풀이 작성

(注記) 풀이작성 안내
  • 본문에 코드를 삽입할 경우 에디터 우측 상단의 "코드삽입" 버튼을 이용 해 주세요.
  • 마크다운 문법으로 본문을 작성 해 주세요.
  • 풀이를 읽는 사람들을 위하여 풀이에 대한 설명도 부탁드려요. (아이디어나 사용한 알고리즘 또는 참고한 자료등)
  • 작성한 풀이는 다른 사람(빨간띠 이상)에 의해서 내용이 개선될 수 있습니다.
풀이 작성은 로그인이 필요합니다.
목록으로
코딩도장

코딩도장은 프로그래밍 문제풀이를 통해서 코딩 실력을 수련(Practice)하는 곳입니다.

random x 2
연관 문제

언어별 풀이 현황
전 체 x 41
python x 26
java x 8
기 타 x 5
cpp x 2
코딩도장 © 2014 · 문의 [email protected]
피드백 · 개인정보취급방침 · RSS

AltStyle によって変換されたページ (->オリジナル) /