2024-11-04






java.lang.NullPointerException: Cannot invoke "String.length()" because "pInfo" is null
at exam.ProductSearch_S.main(ProductSearch_S.java:18)
package exam;
public class ProductSearchData_S {
// 다차원 배열 선언
String[][] proTable;
public ProductSearchData_S() {
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인치 최신 모델";
} // 기본 생성자
String search(String pName) {
String productInfo = null;
for(int i=0; i<proTable.length; i++) {
if(pName.equals(proTable[i][0])) {
productInfo = proTable[i][1];
}
}
return productInfo;
} // search() 메서드 end
}
package exam;
import javax.swing.JOptionPane;
public class ProductSearch_S {
public static void main(String[] args) {
String productName =
JOptionPane.showInputDialog("검색할 상품명을 입력하세요.");
ProductSearchData_S psd = new ProductSearchData_S();
String pInfo = psd.search(productName);
try {
pInfo.length(); // 예외가 발생할 가능성이 있는 코드
// 검색 결과가 productName() 메서드에서 없는 경우 기본값인 "null" 반환
JOptionPane.showMessageDialog(null, pInfo); // 예외가 없는 경우 실행.
}catch(Exception e) {
// 에러가 발생했을 때 처리할 문장.
JOptionPane.showMessageDialog(null, "해당 상품이 없습니다.");
e.printStackTrace();
}
}
}'Java > 기초 내용 정리' 카테고리의 다른 글
| Java(GUI)_ETC_17 (0) | 2024.11.04 |
|---|---|
| Java(GUI)_JMenu_16 (0) | 2024.11.04 |
| Java(Exception)_09 (3) | 2024.11.04 |
| Java(Exception)_08 (0) | 2024.11.04 |
| Java(Exception)_07 (0) | 2024.11.04 |