【问题标题】:Setting a scanner object to null [closed]将扫描仪对象设置为 null [关闭]
【发布时间】: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


【解决方案1】:

将变量设置为 null 并不会消除所使用的资源。您需要做的是在使用完扫描仪后关闭

myScanner.close();

这将允许该对象使用的任何资源被释放并可以再次使用。如果你这样做,并且如果你尽可能在最本地的范围内声明它,则不需要将变量设为空。


至于您的实际问题,请注意您没有主要方法来向我们展示您如何测试它,也没有输入类的代码,这个输入类正在扩展。很难测试您的代码以了解您为什么需要这个 kludge。我担心你正在修复错误的错误。

【讨论】:

    【解决方案2】:

    在每个方法结束时,您调用setScannersetScanner 方法将类的扫描器对象更改为null,这意味着下次调用方法时实际上是在使用空扫描器。

    只是不要在方法结束时调用setScanner;可以多次使用同一个扫描仪对象而不会出现任何问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-19
      • 2014-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-05
      • 2014-10-26
      相关资源
      最近更新 更多