2012-12-08 3 views
1

다음은 상태 입력이 유효한지 확인하는 전자 제품의 생성자입니다. 내 main()에서 그러나클래스로 잘못된 입력 처리

public Electronics(String name, double price, int quantity, double weight, boolean frag, String s) 
    { 
     super("Electronics",name,price,quantity,weight); 
     fragile=frag; 
     s=s.toUpperCase(); 
     if(checkState(s)==true) 
     { 
      state=s; 
     } 
     else 
     { 
      out.println("ERROR - not a valid state abbreviation"); 
     } 
    } 

, 나는 이런 일이 :

public List<Item> shoppingCart = new ArrayList<Item>(); 
temp= new Electronics(name,price,quantity,weight, fragile, state); 
... 
shoppingCart.add(temp); 

그래서 국가의 약어가 유효하지 않은 경우에도, (그냥 상태가 유효하지 않음을 출력합니다)를하지만, 객체입니다 여전히 ArrayList에 추가됩니다. 상태 약어가 올바르지 않은 경우 추가를 중단하려면 어떻게해야합니까?

+0

: 주요 방법

public boolean check(){ if(checkState(s)==true) { state=s; return true; } else { out.println("ERROR - not a valid state abbreviation"); return false; } } 

: thecheckState()에 대한 호출이 true를 반환하는 경우 검사

public Electronics(String name, double price, int quantity, double weight, boolean frag, String s) { super("Electronics",name,price,quantity,weight); fragile=frag; s=s.toUpperCase(); } 

방법 오류 메시지를 인쇄하는 대신 IllegalArgumentException을 던져 주시겠습니까? 그렇게하면 목록에 추가되는 것을 방지하고 상태가없는 개체가 만들어지지 않도록 방지 할 수 있습니다. – pabrantes

답변

1

너는 throw an Exception이어야하고 너의 main()에서 이것을 처리해야한다. 아마 IllegakArgumentException이 여기에 가장 적합 할 것이다. 같은

뭔가 : 주에서

... 
    else 
    { 
     throw new IllegalArgumentException("..."); 
    } 
    ... 

: 예외가 생성자에 의해 throw 될 경우, 프로그램이 목록에 요소의 삽입에 도달하지 않습니다

public List<Item> shoppingCart = new ArrayList<Item>(); 
try { 
    temp= new Electronics(name,price,quantity,weight, fragile, state); 
    ... 
    shoppingCart.add(temp); 
} catch (IllegalArgumentException e) { 
    //handle exception 
} 

참고.

0

예외를 throw해야합니다. IllegalArgumentException가 그 것처럼 들립니다. 그런 다음 생성자가 예외를 throw하여 목록에 추가하지 않겠습니까

0

생성자는 인스턴스 변수를 초기화하기위한 용도로만 사용됩니다. 별도의 메소드 클래스 검사를 수행하여 부울 변수를 반환합니다. 생성자 초기화 인스턴스 변수 : 그것은 잘못된 상태의 약어 있다면

public List<Item> shoppingCart = new ArrayList<Item>(); 
temp= new Electronics(name,price,quantity,weight, fragile, state); 
... 
if(temp.check()){ 
shoppingCart.add(temp); 
} 
else { 
    //check returned false 
    }