점프 투 자바

SUADI·2022년 4월 12일

자료형 연습 문제를 풀어 보았다. 문제를 두 번을 풀어보고 포스팅하면서 복습한 것까지 치면 총 문제를 세 번을 보게 되었는데 해답과 내 풀이가 다른 것이 흥미로웠고, 심지어 풀 때마다도 풀이가 달라져서 재미있었다. 일부러 다른 풀이법을 고민해 보는 것도 실력 향상에도 도움이 될 것같고 재미있기도 하다.

1. 평균 점수 구하기

  • 국어 - 80점, 수학 - 75점, 영어 - 55점
		// 내 풀이
        HashMap<String, Integer> score = new HashMap<>();
        score.put("국어",80);
        score.put("영어",75);
        score.put("수학",55);

        int sum = 0;
        for (int i : score.values()) {
            sum += i;
        }
        System.out.println(sum/score.size());

아직 점프 투 자바를 통해서 반복문을 배우진 않았지만 이미 알고 있으므로 for문을 이용해 풀었다. 여기서 한가지 몰랐던 사실은
for문의 괄호 안이다. 지금까지는 (초깃값,범위,증감) 이렇게 지정해 두고 사용했었는데 int i : score.values()로 지정하면 score의 value값들이 차례로 i에 대입된다는 사실을 알게 되었다.

해답지에서는 HashMap 조차도 사용하지 않고 점수들을 각각 선언해서 계산했다.

2. 홀짝 판별

  • 13이 홀수인지 짝수인지 판별
	    boolean b = 13 % 2 == 0;
        System.out.println(b); // false

boolean 자료형을 이용하여 b에 13 % 2 == 0 명제를 저장해놓고 출력하여 flase가 나왔으므로 홀수임을 알 수 있다.

3. 주민번호 앞자리 출력

  • "123456-1234567" 앞자리 출력(substring 이용)
		// substring을 이용한 해답 풀이
        String n1 = idNum.substring(0,6);
        System.out.println(n1);
        // 내 풀이
        String idNum = "123456-1234567";
        String[] splitIdNum = idNum.split("-");
        String birth = splitIdNum[0];
        System.out.println(birth);

내 풀이에서는 split을 이용하여 두개의 문자열을 String[] 문자열 배열에 각각 저장해서 앞자리만 출력하였다.

4. 특정 위치 출력

  • 주민번호 남녀 구분
        String idNUm = "123456-1234567";
        System.out.println(idNUm.charAt(7));

charAt은 문자열의 위치에 따른 값을 추출해주는 메소드이다.

5. replace

  • "a:b:c:d" -> "a#b#c#d" 변경
        String s1 = "a:b:c:d";
        System.out.println(s1.replace(":","#"));

6. 내림차순 정렬

  • [1,3,2,4,5] -> [5,4,3,2,1]
        ArrayList<Integer> n1 = new ArrayList<>(Arrays.asList(1,3,2,4,5));
        System.out.println(n1);
        n1.sort(Comparator.reverseOrder());
        System.out.println(n1);

sort(Comparator.reversoOrder())을 통해 리스트의 값을 내림차순으로 정렬할 수 있다. 참고로 오름차순은 sort(Comparator.naturalOrder())이다.

7. 리스트 값을 뽑아 문자열 만들기.

  • ["Life", "is", "too", "short"] -> Life is too short
        ArrayList<String> words = new ArrayList<>(Arrays.asList("Life","is","too","short."));
        System.out.println(words);
        String sentence = "";
        for (int i=0; i< words.size(); i++) {
            sentence += words.get(i);
            sentence += " ";
        }
        System.out.println(sentence);

여기서도 for문을 사용했다. 해답과의 차이는 for문 유무이다.
먼저 빈 문자열을 하나 선언을 한다. 그 후에 for문을 이용해서 word 리스트에서 차례대로 값들을 get으로 추출한다. 그다음 띄어쓰기를 위해 " "를 추가한다.

8. remove

        HashMap<String, Integer> grade = new HashMap<>();
        grade.put("A",90);
        grade.put("B",80);
        grade.put("C",70);

        System.out.println(grade.remove("B")); // 80
        System.out.println(grade); // {A=90, B=70}

9. 리스트에서 중복된 숫자 제거

  • 중복된 값이 없는 set의 특성 이용
        ArrayList<Integer> num = new ArrayList<>(Arrays.asList(1,1,1,1,2,2,2,3,3,3,4,4,5,5,6,6,8));
        System.out.println(num); 
        HashSet<Integer> n = new HashSet<>(num);
        num = new ArrayList<>(n);
        System.out.println(num);

중복된 값이 있는 리스트를 HashSet으로 새로 저장을 한다. 그 후에 중복이 사라진 데이터를 다시 list로 재저장을 한다.

10. enum

  • 매직넘버 제거하고 enum이용해서 커피이름 검색하면 가격 알려주는 프로그램 작성
// 문제
import java.util.HashMap;

public class Sample {
    static void printCoffeePrice(int type) {
        HashMap<Integer, Integer> priceMap = new HashMap<>();
        priceMap.put(1, 3000);  // 1: 아메리카노
        priceMap.put(2, 4000);  // 2: 아이스 아메리카노
        priceMap.put(3, 5000);  // 3: 카페라떼
        int price = priceMap.get(type);
        System.out.println(String.format("가격은 %d원 입니다.", price));
    }

    public static void main(String[] args) {
        printCoffeePrice(1);  // "가격은 3000원 입니다." 출력
        printCoffeePrice(99);  // NullPointerException 발생
    }
}

여기서 매직넘버(1,2,3과 같은 상수로 선언하지 않은 수를 의미)를 제거하기 위해서는 enum이라는 메소드를 사용해야 한다. enum에 대해서는 아직 이해도가 그리 높지는 않지만 최대한 풀어 보았다.
먼저 enum을 통해 coffee이름을 저장한다.

import java.util.HashMap;

public class Sample {

	enum coffeeType {
    	Americano,
        Ice_Americano,
        Cafe_Latte
    }
    
    static void printCoffeePrice(int Type) {
    	...
    }
    
    public static void main(String[] args) {
    	...
    }
}

어떤 클래스가 상수만으로 이루어져있다면 class로 선언할 필요없이 enum으로 선언하면 된다. 그 다음은 printCoffeePrint 메소드를 변경해 보겠다.

import java.util.HashMap;

public class Sample {

	enum coffeeType {
		...
    }
    
    static void printCoffeePrice(coffeeType type) {
    	HashMap<coffeeType, Integer> priceMap = new HashMap<>();
        priceMap.put(coffeeType.Americano, 3000);  
        priceMap.put(coffeeType.Ice_Americano, 4000); 
        priceMap.put(coffeeType.Cafe_Latte, 5000); 
        
        int price = priceMap.get(type);
        System.out.println(String.format("가격은 %d원 입니다.", price));
        
    }
    
    public static void main(String[] args) {
    	printCoffeePrice(coffeeType.Americano); 
        // 가격은 3000원 입니다. 출력
    }
}

0개의 댓글