[21.03.08~] JAVA

9day _정수 각 자리값 추출, 윤년 구하기, 카드번호 **** 마스킹, 주민번호 정보 추출, 로또번호 생성기(중복제거)

습관그뤠잇 2021. 3. 18. 16:59

123456 값을 1+2+3+4+5+6=21로 각 자리 가져오기

int money = 1234567;
int sum = 0;

[1] 아스키 코드 값인 '0'=48빼서 처리하기

//moneyS.charAt(i) -> char
//'0' = 아스키 48  
//'1' = 아스키 49(char) --> -48 = 1 하면 맞는 숫자 1이 나옴

String moneyS = money+""; // "1234567"
int len = moneyS.length(); // 7
for (int i = 0; i < len; i++) {
    sum += moneyS.charAt(i)-48; //'0'=아스키48 '1'=아스키49니까 -48하면 1
    System.out.printf("%s + ",moneyS.charAt(i)-48);
    }
System.out.printf("\b= %d\n" , sum);
//결과: 1 + 2 + 3 + 4 + 5 + 6 + 7 + = 28

[2] %10값(=7) 얻고난 후 /10값(=123456) 대입 (몫이 0이 아닐때까지만 반복)

while (money != 0) {
    System.out.printf("%d + ", money % 10);
    sum += (money %10 );
    money = money / 10;
  }
System.out.printf("\b= %d\n" , sum);
//결과 : 7 + 6 + 5 + 4 + 3 + 2 + 1 + = 28

//이 작업을 반복할 것. money의 몫이 0 이 아닐 때까지
/*      System.out.println( money % 10 ); // 7
        System.out.println( money / 10 ); // 123456
        money = money / 10;                  
        // money에 123456 대입 후 한 값씩 가져오기 반복
                                                         */

로또 뽑기

요구사항 분석이 더 중요함 그래서 자세히 읽어보고 설계해야 함!
https://www.dhlottery.co.kr/gameInfo.do?method=gameMethod

자동/ 반자동(1-5개 번호 중 원하는 번호 선택 후 나머지는 임의로 부여받기)/ 수동이 있음

1등 당첨자 없으면 이월되지만 연속 이월은 2회로 제한

매주 토요일 오후 8시 45분경 추첨

토욜 8시 ~ 일욜 오전6시 판매안함

[ 로또번호 발생시키기 -> 배열에 추가 -> 인쇄하듯 출력 ]

카드번호 일부 마스킹하기 (****)

String.join("-", 배열명);

: 쪼인한거 반환하기 위한 코딩 예) String.join("-", cards);
card라는 배열을 -로 쪼인하겠다 . 위에 주루룩 쓴거 내용

String card = "5423-1234-3333-4321";
String [] cards = card.split("-"); // 넷씩 잘라서 cards 배열에 넣을 것임
//System.out.println(cards[0]); //5423

//0~3 난수만들어서 / 랜덤으로 뽑힌 난수값 자리 *로 초기화할 것
int idx = (int)(Math.random()*4); //idx = 별로 바꿀 위치값(0~3사이)
cards[idx] = "****";

String changeCard = String.join("-", cards); //쪼인한거 반환하기 위한 코딩
System.out.println(changeCard);
//결과: 5423-1234-3333-4321

윤년 leap year 구하기

package days09;

import java.util.Scanner;

public class _LeapYearSample {

    public static void main(String[] args) {
        int year; //년도는 사칙연산하는 경우가 많으니 int로 선언

        Scanner scanner = new Scanner(System.in);
        System.out.println("> 년도를 4자리로 입력하세요.");
        year = scanner.nextInt();

        if ( isLeapYear(year) ) {
            System.out.println("윤년 leap year");
        } else {
            System.out.println("평년 common year");
        }


    }//main


    //boolean이라서 true, false 값이 모두 있어야 함
    public static boolean isLeapYear(int year) {
        if(year % 4 == 0 && year % 100 != 0 || year % 400 == 0)  return true;
        else                                                    return false;
    }

    //년도를 입력받아 윤년/평년 true, false 값으로 반환하는 메서드 만들고 자주 쓸것임



}

주민번호 7번째자리(성별식별자 자리) 활용 RRN

package days09;

import java.util.Scanner;

/**
 * @author 조은주
 * @date Mar 18, 2021 - 11:25:56 PM
 * @subject 주민등록번호 : 입력받기, 680201-2~ 중 성별 '2'자리 값으로 여성/내국인/1900년대 확인
 * @content Ex05
 *
 */
public class _RrnSample {

    public static void main(String[] args) {

    //ㄱㄴㄷㄹㅁㅂ - [ㅅ]ㅇㅈㅊㅋㅌㅍ
    // [ㅅ] 자리로 1. 성별 2. 내국인/외국인 3.태어난 세기 확인
    //입력체크용: 123456-7890123

        String rrn;
        rrn = getRRN();
        System.out.printf("> RRN: %s\n", rrn);


        //1. 성별체크
        boolean gender = getGender(rrn); 
        if(gender) {
            System.out.println("남자");
        } else {
            System.out.println("여자");
        }


        //2. 내국인.외국인 체크 _외국인이니? true 내국인이면 false    
        if( isForeigner(rrn) ) {
            System.out.println("외국인");
        } else {
            System.out.println("내국인");
        }

        //3. 몇 세기인지century? 1800년대, 1900년대, 2000년대
        System.out.println(getCentury(rrn));

    }//main

private static String getCentury(String rrn) {
char s = rrn.charAt(7);
switch (s - 48) { //-48을 빼거나 (1의 아스키코드=49) '9'로 값받기 뭐든 상관무
case 9: case 0:
    return "1800년대";

case 1: case 2: case 5: case 6:
    return "1900년대";

default:
    return "2000년대";
}

//        "1800년대" 이런식으로 출력되게 짜기
    }

private static boolean isForeigner(String rrn) {
    char s = rrn.charAt(7); 
    switch (s) {   //if(5<= <=8)해도 됨
    case '5': case '6': case '7': case '8':
        return true;
    }
    return false;
    }

private static boolean getGender(String rrn) {

    char s = rrn.charAt(7); //ㅅ 성별 값 char에 저장 -> '2'임 (홑따옴표 안의 2)    

     return ( s - 48) % 2 ==1 ? true : false ;


}

private static String getRRN() {

    String rrn;

    String regex = "\\d-\\d";
    boolean flag = false; //true이면 다시 입력하라고 알려주도록


    do {
        if(flag) System.out.print("[다시]: ");
        System.out.print("> 주민등록번호 입력?: ");
        Scanner scanner = new Scanner(System.in);
        rrn = scanner.nextLine();
     } while ( flag =!rrn.matches(regex) );

    return rrn;
    }

}//class

로또 난수 발생시키고 중복제거 + 출력

package days09;

/**
 * @author 조은주
 * @date Mar 18, 2021 - 11:33:27 PM
 * @subject 로또 번호 : 난수 발생시키기+중복제거(fillLotto), 발생된 난수 출력(printLotto)
 * @content
 *
 */
public class _LottoSample {

    public static void main(String[] args) {


        int [] lotto = new int[6]; 

        fillLotto(lotto);

        printLotto(lotto);


    } // main

    private static void printLotto(int[] lotto) { 
        for (int i = 0; i < lotto.length; i++) {
            System.out.printf("[%02d]", lotto[i]);
        }
        System.out.println();
    }

    // 1~45 임의의 수(난수)를 lotto 배열에 채워넣는 메서드(함수)
    private static void fillLotto(int[] lotto) {

        int  n, idx = 0; //아예 첫자리 lotto[0]부터 검증    

        while ( idx <= 5 ) {
            n = (int)( Math.random()*45 ) +1;
            System.out.println( n );
            // 로또번호 중복체크
                if(! isDuplicateLottoCheck(lotto, idx, n)) { 
                    lotto[idx] = n; 
                    idx++;
                }      
        } // while

    }
  //복잡한 구문은 함수로 또 빼야 가독성이 좋음(중복체크)
  public static boolean isDuplicateLottoCheck(int [] lotto, int idx, int n) {
    for (int i = 0; i < idx; i++) {
          if(lotto[i] == n )return true;
        }
    return false;
  }


} // class