switch문
2023. 9. 12. 15:21ㆍjava


package ex05;
import java.util.ArrayList;
import java.util.Scanner;
public class main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in); // 도구 생성
ArrayList<poke> pocketmons = new ArrayList<poke>();
while(true) {
System.out.println("[1]추가 [2]삭제 [3]검색");
int choice = sc.nextInt();
switch(choice) {
case 1:
System.out.print("이름 : ");
String name = sc.next();
System.out.print("출몰지 : ");
String area = sc.next();
System.out.print("공격력 : ");
int attack = sc.nextInt();
System.out.print("방어력 : ");
int shield = sc.nextInt();
poke po = new poke(name,area,attack,shield);
break; //case 1 끝
case 2:
//모든 포켓몬 정보 출력
for(int i=0;i<pocketmons.size();i++) {
poke temp = pocketmons.get(i);
System.out.println(temp.getName());
}
//포켓몬 삭제하기
System.out.print("사제할 번호 >> ");
int num = sc.nextInt();
System.out.println(pocketmons.get(num-1).getName()+"삭제!");
pocketmons.remove(num-1);
break;
case 3:
System.out.print("검색 >> ");
String keyword = sc.next();
boolean isOk = false;
//for-each문
for(poke temp : pocketmons) {
//equals => 객체 타입까지 비교 <- poke타입과 String타입끼리 비교니 false뜸(String전용 아님)
if(temp.getName().equals(keyword)) {
// "apple".equals("a") => false
// "apple".contains("a") => true
// "a".contains("apple") => false
System.out.println(temp);
isOk = true;
}//if문끝
}//for문끝
if(!isOk) {
System.out.println("없습니다.");
isOk=false;
}
break;
case 4:
break;
default: //else
System.out.println("잘못입력하셨습니다.");
}//switch끝
} // while 끝
}
}
package ex05;
public class poke {
// 1번 포켓몬 생성 할 수 있는 클래스 설계 <-- 이름(name),공격력(attack),방어력(shield),출몰지역(area)
// vo 구성요소 - 필드, 생성자, get/set
//필드
private String name;
private int attack;
private int shield;
private String area;
//생성자
public poke(String name, String area, int attack, int shield) {
this.name = name;
this.attack = attack;
this.shield = shield;
this.area = area;
}
//get과 set
public String getName() {
return name;
}
public int getAttack() {
return attack;
}
public int getShield() {
return shield;
}
public String getArea() {
return area;
}
//to string
@Override
public String toString() {
return "poke [name=" + name + ", attack=" + attack + ", shield=" + shield + ", area=" + area + "]";
}
// toString 메소드
//객체에 저장된 필드값을 문자열로 만들어 리턴
}'java' 카테고리의 다른 글
| 리펙토링 기법 (0) | 2023.09.13 |
|---|---|
| MVC (4) | 2023.09.12 |
| 객체지향 프로그래밍 생성자,getter,setter (0) | 2023.09.11 |
| 객체지향 (0) | 2023.09.08 |
| 객체 지향 프로그래밍(Object Oriented Programming --> OOP) (0) | 2023.09.08 |