이 코드를 컴파일하려고하면 잘 작동하지만 메서드를 테스트 할 때 첫 번째 메서드는 잘 작동하지만 두 번째 메서드는 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
}
}
스캐너를 null로 설정하는 이유는 무엇입니까? – kviiri
userInput tiwce를 읽었을 때 이전 입력을 사용자가 받아서 스캐너에 assgin하기 때문에 –
@mohamedghassar : 테스트 방법을 보여줄 주요 방법이 없으며 이 클래스가 확장하고있는 입력 클래스. 코드를 테스트하여 왜이 kludge가 필요한지 알기는 어렵습니다. 나는 당신이 잘못된 오류를 고치고있는 것을 두려워합니다. –