当我尝试编译此代码时,它运行良好,但是当我想测试方法时,第一种方法运行良好,但第二种方法抛出一个等于 null 的异常错误指针,但是如果我更改scanner = null;
为scanner = new Scanner(System.in);
它运行良好,那么我该如何无需每次都创建新扫描仪即可解决此问题
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
}
}