在 Net Beans 的同一个项目中使用不同的包时遇到问题 IDE

Trouble in using different packages in same project in Net Beans IDE

我是一名在校学生,我正在使用 Net beans IDE 编写 java 程序,而不是创建项目。

现在,我正面临这个问题。我在同一个项目中有两个包。一个是我创建的用户定义的实用程序包。这有一个程序,该程序定义了用于打印和将双维数组作为输入的方法。它没有主要方法。

我的一小部分class如下。我只给出我遇到问题的部分。

package UserDefinedUtilities;
import java.util.*;
public class ArrayUtilities2D {
  public int[][] InputInt(int m, int n){
      Scanner kb = new Scanner (System.in);
      System.out.println();
      int arr[][] = new int[m][n];
      System.out.println("Enter the array elements: ");
      for (int i = 0; i < m; i++){
          for (int j = 0; j < n; j++){
              System.out.print("Enter the element in cell (" + i + "," + j + "): ");
              arr[i][j] = kb.nextInt();
          }
      }
      kb.close();
      System.out.println();
      return arr;
  }
}

这是我尝试访问的 class 的输入法。

package AnswerPrograms;
import UserDefinedUtilities.*;
import java.util.*;
public class J124{
    private int m, n;
    private void Input(){
        Scanner kb = new Scanner (System.in);
        System.out.print("Enter the number of rows: ");
        m = kb.nextInt();
        System.out.print("Enter the number of columns: ");
        n = kb.nextInt();
        kb.close();
        int arr[][] = new ArrayUtilities2D().InputInt(m, n); //using the input method from the above class
        System.out.println("The original matrix is: ");
        new ArrayUtilities2D().IntPrint(m, n, arr);
        if (m % 2 == 0){
            Mirror_Even(arr);
        }
        else{
            Mirror_Odd(arr);
        }
    }
    . //other necessary methods are present here
    .
    .
    .
}

在第二个包中,我存储了我的程序。现在,当我尝试使用这种方法从这个 class 获取输入时,会显示以下几行:

Exception in thread "main" java.util.NoSuchElementException
Enter the element in cell (0,0):    at 
java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at UserDefinedUtilities.ArrayUtilities2D.InputInt(ArrayUtilities2D.java:24)
at AnswersPrograms.J124.Input(J124.java:13)
at AnswersPrograms.J124.main(J124.java:90)
Java Result: 1
BUILD SUCCESSFUL (total time: 5 seconds)

谁能解释为什么会这样?我在 BlueJ 中没有遇到这个问题。为什么在我输入内容之前就出现了 NoSuchElementException?我应该怎么做才能纠正这个问题?我应该更改我的 jdk 吗?

该错误与软件包无关。您的代码编译并运行良好,并且如堆栈跟踪所示,两种方法都被调用。

问题是您正尝试使用扫描仪从 System.in 阅读,但您在阅读前关闭了扫描仪。所以没有什么可读的了。

作为 javadoc says:

If this scanner has not yet been closed then if its underlying readable also implements the Closeable interface then the readable's close method will be invoked.

所以,当您关闭扫描仪时,您也关闭了 System.in