2013-10-29 2 views
-1

이 코드를 컴파일하려고하면 잘 작동하지만 메서드를 테스트 할 때 첫 번째 메서드는 잘 작동하지만 두 번째 메서드는 null과 같은 예외 오류 포인터를 throw하지만, 이 새로운 스캐너를 매번 생성하지 않고 나는이 문제를 해결할 수있는 방법을 너무 잘 작동 scanner = new Scanner(System.in);-scanner = null;을 변경스캐너 개체를 null로 설정

public class Sca extends input 
{ 

    private Scanner scanner; 
    private String userInput; 

    public ArrayShoppingList11() 
    { 
     super(); 
     scanner = new Scanner(System.in);  
    } 


    protected void addCar() 
    { 
     System.out.println("Please enter the name of the Car to be added"); 
     userInput = scanner.nextLine(); 
     super.add(userInput); 
     setScanner(); 

    } 

    protected int getPosition() 
    { 
     System.out.println("Please enter the name of the car"); 
     userInput = scanner.nextLine(); 
     int z = super.indexOf(userInput); 
     System.out.println("The position of " + userInput + "is: " + z); // used for the main class Testing purposes 
     setScanner(); 
     return z; 
    } 
     private void setScanner() 
    { 
     if(scanner != null) 
     { 
      scanner = null; 
     } 

    } 
} 

공용 클래스 홈페이지 {

public static void main(String[] args) { 


    ArrayShoppingList1 a = new ArrayShoppingList1(); 



    a .printList(); 
    a.addCar(); 
    a .getPosition();// returning the position of an item using name of the item 


    a .checkEmpty(); 
    a.additem(); 
    a .printList(); 
    a .removeItem();// removing the item using the index of the item 
} 

}

+4

스캐너를 null로 설정하는 이유는 무엇입니까? – kviiri

+0

userInput tiwce를 읽었을 때 이전 입력을 사용자가 받아서 스캐너에 assgin하기 때문에 –

+0

@mohamedghassar : 테스트 방법을 보여줄 주요 방법이 없으며 이 클래스가 확장하고있는 입력 클래스. 코드를 테스트하여 왜이 kludge가 필요한지 알기는 어렵습니다. 나는 당신이 잘못된 오류를 고치고있는 것을 두려워합니다. –

답변

1

각 방법의 끝에서 setScanner으로 전화하십시오. setScanner 메서드는 클래스의 스캐너 개체를 null으로 변경합니다. 즉, 다음에 메서드를 호출하면 실제로는 null 스캐너가 사용됩니다.

메서드의 마지막에 setScanner을 호출하면 안됩니다. 동일한 스캐너 개체를 아무 문제없이 여러 번 사용할 수 있습니다.

2

변수를 null로 설정해도 사용 된 리소스가 제거되지 않습니다. 당신이해야 할 것은 당신이를 통해 그것을 사용하여 수행 할 때 가까운 스캐너이다 :

myScanner.close(); 

이이 객체에 의해 사용되는 자원이 해제되고 다시 사용될 수 있음을 수 있습니다. 이렇게하면 가장 가까운 지역 범위에서 선언하면 변수를 null로 지정할 필요가 없습니다. 실제 질문에 대해서는


, 당신은 당신이 이것을 테스트하는 방법을 우리에게 보여 할 주요 방법이없는 점에 유의 없으며 입력 클래스에 대한이 하나가 확장 된 하나의 코드를해야합니까. 코드를 테스트하여 왜이 kludge가 필요한지 알기는 어렵습니다. 나는 당신이 잘못된 오류를 고치고있는 것을 두려워합니다.

관련 문제