[Java] Map 연습문제 3
1. 조건
- 1.입력 2.출력 3.삭제 4.종료 (종료를 누를 때까지 무한루프)
- ‘1’ 입력 시 과일 이름을 입력 받는다. (저장 성공 여부 출력)
- ‘2’ 입력 시 값이 있으면 출력, 없으면 “비어있습니다.”를 출력한다.
- ‘3’ 입력 받은 과일을 삭제한다. (삭제 성공 여부 출력)
- ‘4’ 프로그램 종료
- “1-4” 외의 값을 입력 받을 경우 “잘못 입력했습니다.” 출력
2. 정답 코드
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
List<String> fruits = new ArrayList<>();
while (true) {
System.out.println("1.입력 2.출력 3.삭제 4.종료");
int num = scan.nextInt();
scan.nextLine(); // 남은 \n을 가져감 (엔터 두 번 쳐야 하는 번거로움 제거)
if (num == 1) {
System.out.print("과일 이름을 입력하세요.");
String fruit = scan.nextLine();
boolean isInsert = fruits.add(fruit);
System.out.println(isInsert ? "입력 성공" : "입력 실패");
} else if (num == 2) {
if (fruits.isEmpty()) {
System.out.println("비어있습니다.");
continue;
}
for (String print : fruits) {
System.out.println(print);
}
} else if (num == 3) {
System.out.println("삭제할 과일을 입력하세요.");
String del = scan.nextLine();
System.out.println(fruits.remove(del) ? "삭제 완료" : "삭제 실패");
} else if (num == 4) {
System.out.println("종료합니다.");
break;
} else {
System.out.println("잘못 입력하셨습니다.");
}
}
}
위 정답 코드를 보면 중복 값을 검사하는 코드는 존재하지 않는다.
만약 중복 값을 검사하는 코드를 추가한다면?
if (num == 1) {
System.out.print("과일 이름을 입력하세요.");
String fruit = scan.nextLine();
if (fruits.contains(fruit)) { // List에 입력값이 존재하는지 확인
System.out.println("중복입니다.");
System.out.print("과일 이름을 입력하세요.");
fruit = scan.nextLine(); // 중복일 경우 과일을 다시 입력 받음
}
boolean isInsert = fruits.add(fruit);
System.out.println(isInsert ? "입력 성공" : "입력 실패");
}
3. Set?
중복 코드를 추가하며 든 생각이다.
- 과일(입력값)을 바구니(List)에 담고
- 과일바구니에 어떤 과일이있는지
- 원치않는 과일, 중복 과일 제거
위 기능을 구현할 것이라면 Set 인터페이스가 더 효율적이지 않을까?
Set은 중복값 저장자체가 불가능하기 때문이다.
중복일 경우 add()에서 false를 반환하기 때문에, 아래에 다시 입력 받을 코드만 추가해주면 끝이다.
Set<String> fruits = new LinkedHashSet<>();
while (true) {
System.out.println("1.입력 2.출력 3.삭제 4.종료");
int num = scan.nextInt();
scan.nextLine();
if (num == 1) {
System.out.print("과일 이름을 입력하세요.");
String fruit = scan.nextLine();
boolean isInsert = fruits.add(fruit);
System.out.println(isInsert ? "입력 성공" : "입력 실패");
if (!isInsert) {
System.out.print("과일 이름을 입력하세요.");
fruit = scan.nextLine();
isInsert = fruits.add(fruit);
System.out.println(isInsert ? "입력 성공" : "입력 실패");
}
}
중복일 경우 if문으로 다시 입력을 받는다.
하지만…
입력값이 기억하지 못할 정도로 많아지거나, 다른 사람이 입력할 경우?
물론 입력 전에 출력 후 없는 과일을 입력하는 것이 베스트일 것이다.
그러나 언제나 그렇듯 예외는 존재하므로, 중복값이 나오지 않을 때까지 무한루프로 입력을 받아야 한다.
‘1’ 입력 시 조건문 안으로 들어가고, false면 무한루프를 돌리는 코드.
do-while이다.
if (num == 1) {
boolean isInsert;
do {
System.out.print("과일 이름을 입력하세요.");
String fruit = scan.nextLine();
isInsert = fruits.add(fruit);
System.out.println(isInsert ? "입력 성공" : "중복입니다.");
} while (!isInsert);
}
중복값 제거를 위해 선택했던 Set의 나비효과…
Leave a comment