본문 바로가기

카테고리 없음

내일배움캠프 사전캠프 TIL/4일차 자바 응용 3단계

문제 풀이 도움되는 사전 지식

1.아스키 코드

 

입력값이 알파벳이고 a - z 포함되는지 확인하기 위해 필요했다.

단어 맞추기 게임

 

2 - a 입력값이 a - z 사이의 알파벳

        //알파벳인지 체크 97 - 122 사이면 알파벳임
        int ic = value.charAt(0);
        if(122 < ic || ic < 97){
            System.out.println("소문자 알파벳을 입력해주세요!");
            System.out.println("------------------------------");
            return 0;
        }

 

> 이 부분이 문제였지만 구글링을 통해 아스키코드로 해결했다.

2 - b 한 글자로 입력받기

      // 입력한 값이 한글자가 맞는지 체크
        if(value.length() > 1 || value.trim().equals("")){
            System.out.println("한글자 이하로 작성해 주세요");
            System.out.println("------------------------------");
            return 0;
        }

 

> trim() 으로 여백제거 후 equals로 비교 해준다.

 

2 - c 이미 입력한 값이면 다시 입력

//처음 입력한 값이면 list에 저장하는 코드
if(list.indexOf(value) == -1){
    list.add(value);
    System.out.println("이미 사용된 알파벳 -> " + list.toString());
    System.out.println("------------------------------");
}else{
    System.out.println("중복된 값입니다!");
    System.out.println("이미 사용된 알파벳 -> " + list.toString());
    System.out.println("------------------------------");
    return 0;
}

 

미리 리스트를 선언해서 입력된 값들을 저장한다. 그래서 중복 값은 다시 입력받고

편의상으로 이미 사용된 리스트를 보여준다.

 

2 - d 단어에 포함되는 알파벳을 입력했으면 위치를 보여주고 다시 입력 받음

//정답에 포함된 값인지 체크
List<Integer> cntList = new ArrayList<>();

 

 

>  정답을 맞췄을 경우 맞은 알파벳의 자릿수를 저장하기 위해 cntList를 선언

 

        int cnt = answer.indexOf(value);
        //정답에 포합되있으면 몇개인지 체크
        if(cnt != -1){
            while(cnt != -1){
                if(cnt != -1){
                    cntList.add(cnt);
                    cnt = answer.indexOf(value,cnt+1);
                }
            }
         }

 

 

> String의 indexOf() 함수를 활용하여 어디에 포함된지 확인한다 여러개가 있을 경우를 생각해서

cnt = answer.indexOf(value,cnt+1); 자릿수를 지정해줘서 다시 찾는다

 

for(int i = 0 ; i < answer.length(); i++){
    for(int j = 0 ; j < cntList.size(); j++){
        if(i == cntList.get(j)){
            viewVar.set(cntList.get(j),value);
        }
    }
}

 

> 위에서 찾은 위치로 정답을 저장하는 리스트에 옮겨서 저장해준다.

 

2 - e 정답에에 포함되지 않는 경우 생명력 감소

static int life = 9;

 

 

> 간단하고 클래스 변수로 선언하고 틀렸으면 -1로 했다

 

 

 

전체 코드

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Study3 {

static List<String> list = new ArrayList<>();
static int life = 9;
static List<String> viewVar = new ArrayList<>();

    public static void main(String[] args) {
		
        //인스턴스생성
        Study3 study3 = new Study3();
        String answer = study3.randomStr();
        //사용자에게 몇글자인지 알려줌
        System.out.println(answer.length() + "글자 입니다!!");
        // ckNum이 1이면 게임 종료
        int ckNum = 0;
        while(ckNum == 0){
            Scanner sc = new Scanner(System.in);
            //사용자가 값 입력
            String val = sc.next();
            System.out.println(val);
            ckNum = study3.valueCheck(answer,val);
        }
    }
    //랜덤한 단어 선택하는 코드
    public String randomStr(){
        String[] dic = {"airplane","apple","arm", "bakery", "banana", "belt", "bicycle", "biography", "bowl", "broccoli", "bus", "car",
                "carrot", "chair", "cherry", "cinema", "class", "classroom", "cloud", "coat", "cucumber", "desk", "dictionary", "dress",
                "ear", "eye", "fog", "foot", "fork", "fruits", "hail","hand", "head","helicopter", "jacket", "leg", "lettuce", "library",
                "magazine", "mango", "mouth", "newspaper", "nose", "notebook", "novel", "onion", "orange", "peach", "pharmacy", "pineapple",
                "plate", "pot", "shirt", "shoe", "shop", "sink", "skateboard", "ski", "skirt","sky", "snow", "sock", "spinach", "spoon",
                "stationary", "stomach", "strawberry", "supermarket", "sweater", "teacher", "thunderstorm", "tomato", "trousers", "truck",
                "vegetables", "vehicles", "watermelon", "wind"
        };
        //난수생성
        int rn = (int)Math.floor(Math.random()* dic.length);
        //랜덤 정답 생성
        String str = dic[rn];
        for(int i = 0 ; i < str.length(); i++){
            viewVar.add("_");
        }
        return str;
    }

    //사용자 입력값 체크
    public int valueCheck(String answer,String value){

        // 입력한 값이 한글자가 맞는지 체크
        if(value.length() > 1 || value.trim().equals("")){
            System.out.println("한글자 이하로 작성해 주세요");
            System.out.println("------------------------------");
            return 0;
        }
        //알파벳인지 체크 97 - 122 사이면 알파벳임
        int ic = value.charAt(0);
        if(122 < ic || ic < 97){
            System.out.println("알파벳을 입력해주세요!");
            System.out.println("------------------------------");
            return 0;
        }
        //처음 입력한 값이면 list에 저장하는 코드
        if(list.indexOf(value) == -1){
            list.add(value);
            System.out.println("이미 사용된 알파벳 -> " + list.toString());
            System.out.println("------------------------------");
        }else{
            System.out.println("중복된 값입니다!");
            System.out.println("------------------------------");
            return 0;
        }

        //정답에 포함된 값인지 체크
        List<Integer> cntList = new ArrayList<>();
        int cnt = answer.indexOf(value);
        //정답에 포합되있으면 몇개인지 체크
        if(cnt != -1){
            while(cnt != -1){
                if(cnt != -1){
                    cntList.add(cnt);
                    cnt = answer.indexOf(value,cnt+1);
                }
            }
            for(int i = 0 ; i < answer.length(); i++){
                for(int j = 0 ; j < cntList.size(); j++){
                    if(i == cntList.get(j)){
                        viewVar.set(cntList.get(j),value);
                    }
                }
            }
            if(viewVar.indexOf("_")==-1){
                System.out.println("----------승리!!---------------");
                System.out.println("클리어!!");
                System.out.println("------------------------------");
                return 1;
            }
            System.out.println("--------" +cntList.size()+ "개 맞았습니다!---------");
            System.out.println(viewVar.toString());
            System.out.println("------------------------------");
        }else{
            System.out.println("틀렸습니다");
            System.out.println("------------------------------");
            System.out.println(viewVar.toString());
            life -= 1;
            System.out.println("남은 life는 : " + life + " 입니다.");
            System.out.println("------------------------------");
            if(life == 0){
                System.out.println("---------패배...---------------");
                System.out.println("정답은 " + answer + " 였습니다!");
                System.out.println("------------------------------");
                return 1;
            }
        }
        return 0;
    }
}