package exam;
public class ProductSearchData {
String[][] proTable; // 배열 선언
public ProductSearchData() { // 기본 생성자
proTable = new String[3][2];
// [0]열에는 상품명을 저장, [1]열에는 상품정보가 저장.
proTable[0][0] = "세탁기";
proTable[0][1] = "드럼 세탁기 최신형";
proTable[1][0] = "냉장고";
proTable[1][1] = "지펠 냉장고 최신형";
proTable[2][0] = "TV";
proTable[2][1] = "HDTV 150인치 최신모델";
} // 기본 생성자 end
// 상품명을 매개변수로 넘겨 받아서 해당 상품에 대한 정보를 반환하는 메서드
String search(String pName) {
String proInfo = null; // 상품 정보가 저장될 변수
for(int i=0; i<proTable.length; i++) {
if(pName.equals(proTable[i][0])) {
proInfo = proTable[i][1];
}
}
return proInfo;
}
}
package exam;
import javax.swing.JOptionPane;
public class ProductSearch {
public static void main(String[] args) {
String productName =
JOptionPane.showInputDialog("검색할 상품명을 입력하세요.");
ProductSearchData ps = new ProductSearchData();
String productInfo = ps.search(productName);
try {
productInfo.length(); // 예외가 발생할 가능성이 있는 코드
JOptionPane.showMessageDialog(null, productInfo);
}catch(Exception e) {
// 예외가 발생했을 때 처리할 문장.
System.out.println("해당 상품이 없습니다.");
JOptionPane.showMessageDialog
(null, "해당 상품이 없습니다.");
}
}
}
모니터는 객체 배열에 저장되지 않았기 때문에 예외처리되어 '해당 상품이 없습니다'라고 뜬다.
'Back > JAVA' 카테고리의 다른 글
String Class의 특징 및 주요 메서드(StringBuffer, StringTokenizer) (0) | 2021.03.16 |
---|---|
Util 패키지 - Random, Math, Calendar, Arrays (0) | 2021.03.15 |
예외(exception) 처리 (0) | 2021.03.15 |
[심화예제] 메소드 매개변수로 객체를 보내보자 (0) | 2021.03.12 |
final 지정자 (0) | 2021.03.12 |