Random rnd = new Random();
Scanner sc = new Scanner(System.in);
int[] arr = new int[4];
boolean[] check = new boolean[4];
// 1. 중복없이 저장
int i = 0;
int rNum = 0;
while (true) {
rNum = rnd.nextInt(4)+1;
if (i > 3) {
break;
}
if (check[rNum-1] == false) {
check[rNum-1] = true;
arr[i] = rNum;
i += 1;
}
}
System.out.println(Arrays.toString(arr));
System.out.println(Arrays.toString(check));
// 2. 저장 값 입력값과 비교
int inputIndex = 0;
// int resultIndex = 0;
i = 0; // 인덱스 증가값
while (true) {
if (i >= 4) {
break;
}
System.out.println((i+1) + " 번째 방번호 입력 (0~3)");
inputIndex = sc.nextInt();
// for (int j = 0; j < arr.length; j++) {
// if (arr[j] == i+1) {
// resultIndex = j;
// }
// }
// 굳이 비교할 필요 없이 arr에 입력받은 index 증가값과 맞는지 비교
if (arr[inputIndex] == i+1) {
arr[inputIndex] = 9;
i += 1;
System.out.println("정답");
} else {
System.out.println("틀림");
}
System.out.println("\n"+Arrays.toString(arr));
}
sc.close();
주석처리한 부분은 답안예시를 안보고 작성했던 부분이다. 답안 예시를 보니 회원가입에 이어 또 얼마나 비효율적인가 새삼 깨달았다.
랜덤으로 복권배열에 1 또는 7 을 저장한다.
화면은 { * * * * * * * } 이렇게 출력한다.
인덱스 3개를 고를수있고,
인덱스 3개의 값이 전부 7이면 당첨이다.
[조건1]
반드시 7은 3개이상 있어야 한다.
예) 1,1,7,7,1,7,1
[조건2]
한번 고른 인덱스는 또고를수없다.
예) 2,2,2
Scanner scan = new Scanner(System.in);
int 복권[] = new int[7];
Random ran = new Random();
int c7 = 0;
int c1 = 0;
int index = 0;
for(int i = 1; i ==1;) {
int r = ran.nextInt(2);
if(r == 0 && c7 < 3) {
복권[index] = 7;
index += 1;
c7 += 1;
}else if(r == 1 && c1 < 4) {
복권[index] = 1;
index += 1;
c1 += 1;
}
if(c7 == 3 && c1 == 4) {
break;
}
}
System.out.println(Arrays.toString(복권));
boolean check[] = new boolean[7];
int cCount = 0;
while(true) {
for(int i = 0; i < 7; i++) {
if(check[i] == false) {
System.out.print("*");
}else {
System.out.print(복권[i]);
}
}
System.out.println();
if(cCount == 3) {
break;
}
System.out.println("인덱스 입력 : ");
int sel = scan.nextInt();
if(sel < 0 || sel > 7) {
System.out.println("오류");
continue;
}
if(check[sel]== false) {
cCount += 1;
check[sel] = true;
}else if(check[sel]== true) {
System.out.println("이미선택한자리입니다.");
}
}
int win = 0;
for(int i = 0; i < 7; i++) {
if(check[i] == true && 복권[i] == 7) {
win += 1;
}
}
if(win == 3) {
System.out.println("당첨");
}else {
System.out.println("꽝");
}
이 코드는 랜덤한 1,7이 할당되면
1. 처음 실행 콘솔 {*, *, *, *, *, *, * }
2. 인덱스 2입력시 콘솔 ===> {*, *, 7, *, *, *, * }
이런식으로 하나씩 입력하며 입력받은 인덱스 위치의 수가 보여져야했는데... 또 이해를 잘못했다.
위의 문제 설명을 보고 내가 이해한 것
1. 1,7 할당이 다 되면 콘솔에 {*, *, *, *, *, *, * }
만 출력됨
2. 인덱스 3개 입력받고 중복 유효성 검사 후 맞출때마다 증가값을 줘 전부 맞췄는지 확인
해당 코드
// 이해를 잘못한 문제
Scanner sc = new Scanner(System.in);
Random rnd = new Random();
int[] arr = new int[7];
int rNum = 0;
int sevenCount = 0;
int oneCount = 0;
// 반드시 7은 3개이상 있어야 한다.
int i = 0;
while (true) {
rNum = rnd.nextInt(2);
if ( i >= 7 ) {
System.out.println("복권 생성 완료");
System.out.println(Arrays.toString(arr));
break;
}
if (rNum == 0 && oneCount < 4) {
arr[i] = 1;
oneCount += 1;
i += 1;
} else if (rNum == 1 && sevenCount < 3) {
arr[i] =7;
sevenCount += 1;
i += 1;
}
}
System.out.print("첫번째 7 위치 입력 0~6 : ");
int first = sc.nextInt();
System.out.print("두번째 7 위치 입력 0~6 : ");
int second = sc.nextInt();
System.out.print("세번째 7 위치 입력 0~6 : ");
int third = sc.nextInt();
boolean error = false;
if ( (first > i && first < 0) && (second > i && second < 0) && (third > i && third < 0) ) {
System.out.println("인덱스 에러");
error = true;
}
// 인덱스 유효성 검사2
if (first == second || second == third || first == third) {
System.out.println("같은 인덱스 입력");
error = true;
}
int count = 0;
if (error == false ) {
for (int j = 0; j < arr.length; j++) {
if (arr[first] == 7 && first == j) {
count += 1;
}
if (arr[second] == 7 && second == j) {
count += 1;
}
if (arr[third] == 7 && third == j) {
count += 1;
}
}
}
System.out.println(Arrays.toString(arr));
if (count == 3) {
System.out.println("당첨");
} else {
System.out.println("꽝");
}
답안예시와 해설강의를 안보고 최대한 직접 생각해보며 코딩을 하고 있는데 이처럼 문제 의도를 잘못 유추한게 많다. 결국 이것 또한 좋은 경험이니까 긍정적인 마인드
즉석복권문제) 사이즈가 7인 배열이 있다.
[1. 복권 결과확인] 입력시 "당첨" 또는 "꽝" 출력
1 또는 7을 랜덤으로 배열에 저장한다. [예] 1,7,7,1,1,1,7
7이연속으로 3개이상이면 "당첨" 아니면 "꽝" 이다.
당첨이되면 3000원 획득한다.
꽝이되면 1000원 감소한다.
[조건] 반드시 7은 3개이상 있어야한다.
canner sc = new Scanner(System.in);
Random rnd = new Random();
int[] lottery = new int[7];
int money = 1000;
int select = 0;
int rNum = 0;
while (true) {
System.out.println("[잔액 : " + money + "원]");
System.out.println("[1. 복권 구매] / [2. 돈충전] / [0. 종료]");
System.out.print("메뉴 선택 : ");
select = sc.nextInt();
if (select == 1) {
int oneCount = 0;
int sevenCount = 0;
int index = 0;
int maxCount = 0;
int count = 0;
if (money < 1000) { // 돈이 1000원보다 적을 경우
System.out.println("잔액부족");
continue;
}
while (true) {
if (index == 7) { // 복권 만들면 멈춤
System.out.println("복권 결과확인");
System.out.println(Arrays.toString(lottery));
break;
}
rNum = rnd.nextInt(2);
if (rNum == 0 && oneCount < 4) {
lottery[index] = 1;
index += 1;
oneCount += 1;
} else if (rNum == 1 && sevenCount < 3) {
lottery[index] = 7;
index += 1;
sevenCount += 1;
}
}
for (int i = 0; i < lottery.length; i++) {
if (lottery[i] == 7) {
count += 1;
} else {
count = 0;
}
if (count >= maxCount) {
maxCount = count;
}
}
System.out.println("연속된 7 갯수" + maxCount);
if (maxCount == 3) {
System.out.println("당첨");
money += 3000;
} else {
System.out.println("꽝");
money -= 1000;
}
System.out.println();
} else if (select == 2) {
System.out.print("충전금액 입력 : ");
select = sc.nextInt();
money += select;
System.out.println("충전 후 잔액 : " + money);
} else if (select == 3) {
System.out.println("종료");
break;
} else {
System.out.println("선택 오류");
}
}
System.out.println("최종 금액 : " + money);
문제2보다 오해할 요소가 적어서 문제2에 비해 시간 소요가 적었던거 같다.
Scanner sc = new Scanner(System.in);
int max = 5;
int[] idList = new int[max];
int[] pwdList = new int[max];
int[] moneyList = new int[max];
int id = 0;
int pwd = 0;
int money = 0;
int index = 0;
int count = 0;
int log = -1;
boolean check =false;
//1.회원가입 2.회원탈퇴 3.로그인 4.로그아웃
//5.입금 6.송금 7.조회 8.전체회원목록 0.종료.
while (true) {
if (log != -1) {
System.out.println(log+"님 환영합니다");
for (int i = 0; i < count; i++) { // 로그인했을때 인덱스 저장
if (idList[i] == log) {
index = i;
}
}
} else {
index = 0;
}
System.out.println(Arrays.toString(idList));
System.out.println(Arrays.toString(pwdList));
System.out.println(Arrays.toString(moneyList) + "\n");
System.out.println("[1] 회원가입 [2] 회원탈퇴 [3] 로그인 [4] 로그아웃");
System.out.println("[5] 입금 [6] 송금 [7] 조회 [8] 전체회원목록 [0] 종료");
int select = sc.nextInt();
if (select == 1) {
check = false;
if (count >= 5) { //회원 최대수 (max) 유효성 검사
System.out.println("회원 마감 / 더 이상 추가 불가능");
continue;
}
System.out.print("가입 아이디 입력 : ");
id = sc.nextInt();
// 아이디 중복체크
for (int i = 0; i < count; i++) {
if (idList[i] ==id) {
check = true;
}
}
if (check == true) { // 아이디 중복검사 조건
System.out.println("이미 있는 아이디입니다.");
continue;
}
idList[count] = id;
System.out.print("비밀번호 입력 : ");
pwdList[count] = sc.nextInt();
moneyList[count] = 1000;
System.out.println("회원가입 완료!");
System.out.printf("가입 축하금 %d원 지급!\n", moneyList[count]);
count += 1;
System.out.println();
} else if (select == 2) {
if (log == -1) {
System.out.println("로그인 후 이용 가능");
continue;
}
System.out.println("탈퇴하시겠습니까 [1] Yes [2] No ");
select = sc.nextInt();
if (select == 1) {
// index = 0;
// 삭제하려면 1. log값 인덱스 찾기(로그인 가정
// for (int i = 0; i < count; i++) {
// if (idList[i] == log ) {
// index = i;
// }
// }
// 삭제 후 한칸씩 땡기기 ---> 인덱스부터 한칸씩 count -1까지
for (int i = index; i < count-1; i++) { // 밥먹고 띵킹띵킹
idList[i] = idList[i+1];
pwdList[i] = pwdList[i+1];
moneyList[i] = moneyList[i+1];
}
//인덱스 찾은 후 삭제하기
idList[count-1] = 0;
pwdList[count-1] = 0;
moneyList[count-1] = 0;
log = -1; //탈퇴 후 로그아웃 처리
count -= 1;
System.out.println("탈퇴 완료!");
System.out.println();
} else if (select == 2) {
System.out.println("처음으로 돌아갑니다");
continue;
}
System.out.println();
} else if (select == 3) {
if (log == -1) {
check = false;
System.out.print("아이디 입력 : ");
id = sc.nextInt();
System.out.print("비밀번호 입력 :");
pwd = sc.nextInt();
for (int i = 0; i < count ; i++ ) {
if (idList[i] == id && pwdList[i] == pwd) {
check = true;
break;
}
}
if (check == true) {
log = id;
System.out.println("로그인 성공");
System.out.println("메인으로 돌아갑니다");
} else {
System.out.println("아이디 비밀번호 확인");
}
} else if (log != -1) {
System.out.println("로그인 중에만 이용 가능");
}
System.out.println();
} else if (select == 4) { // 로그아웃
if (log == -1) {
System.out.println("로그인한 회원이 아닙니다");
} else {
System.out.println("로그아웃 성공");
log = -1;
}
System.out.println();
} else if (select == 5) { // 입금
if (log == -1) {
System.out.println("로그인한 회원이 아닙니다");
}
System.out.println("입금 전 금액 : " + moneyList[index]);
System.out.print("입금할 금액 입력 : ");
money = sc.nextInt();
moneyList[index] += money;
System.out.println("입금 후 금액 : " +moneyList[index] );
System.out.println();
} else if (select == 6) { // 이체
if (log == -1) {
System.out.println("로그인한 회원이 아닙니다");
}
check = false;
System.out.println(log+" 님의 현재 금액 : " + moneyList[index]);
System.out.print("이체 아이디 입력 : ");
int transferId = sc.nextInt();
int transferIndex = 0;
// 이체 있는지 검사
for (int i = 0; i < count ; i++) {
if (idList[i] == transferId) {
check = true;
transferIndex = i;
break;
}
}
if (check == false ) {
System.out.println("해당 아이디 없음");
continue;
}
System.out.print("이체 금액 입력 : ");
money = sc.nextInt();
if (money > moneyList[index]) {
System.out.println("이체 금액이 더 큼 잔고 확인 바람");
continue;
}
moneyList[transferIndex] += money;
moneyList[index] -= money;
System.out.println("이체 성공");
System.out.println("남은 잔액 : " + moneyList[index]);
System.out.println();
} else if (select == 7) {
if (log == -1) {
System.out.println("로그인한 회원이 아닙니다");
}
System.out.println(log+"님의 잔액 : "+moneyList[index]);
System.out.println();
} else if (select == 8) {
System.out.println("전체 회원 정보");
System.out.println(Arrays.toString(idList)+"\n");
} else if (select == 0) {
System.out.println("프로그램 종료");
break;
}
}
문제4번은 코딩하다가 '로그인'이라는 공통점을 발견했다. 그래서 로그인시에 해당 회원 인덱스를 저장하고 로그아웃시 인덱스를 초기화해주면 중복코드가 적지 않을까 싶었고 해당 접근은 정답이었다. 이 방법에 문제가 없는지 질문해봤는데 인덱스 연습을 위한거였지 이렇게 접근하는 방법을 깨달았단 것이 인덱스에 대해 이해가 됐다라고 피드백해주셨다.
조금 뿌듯
앞선 포스트의 회원가입 문제의 심화버전인데 해당 문제를 이해하려 노력했고 이 문제는 앞의 코드를 안보고 풀고 에러나면 어디가 문제인지 차근히 뜯어보고 인덱스에 좀 더 친해지는 과정이 되는 문제였다.
여기까지 저번주 붙잡았던 범위에 인상 남던 문제들만 포스팅했다. 인덱스 범위 에러를 징하게 봤지만 앞으로도 더 보겠지 쫄지말자
우리 존재 파이팅