【发布时间】:2013-11-09 09:05:26
【问题描述】:
当我尝试编译这段代码时它运行良好,但是当我想测试方法时,第一种方法运行良好但第二种方法抛出一个等于 null 的异常错误指针,但如果我将 scanner = null; 更改为 @ 987654322@ 它工作正常,所以我怎样才能解决这个问题,而无需每次都创建新的扫描仪
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
}
}
【问题讨论】:
-
为什么将扫描仪设置为空?
-
因为当我阅读 userInput tiwce 时,它只会从用户那里获取旧输入并将其分配给扫描仪
-
@mohamedghassar:你没有主要的方法来告诉我们你是如何测试这个的,你也没有这个扩展的输入类的代码。很难测试您的代码以了解您为什么需要这个 kludge。我担心你正在修复错误的错误。
-
我在添加第二辆车时添加了测试类它只是自己添加它
-
你,可能想把你的班级名称从“Sca”改成...?
标签: java methods null java.util.scanner bluej