0

我一直在为班级做一个小项目,它运行完美,没有问题,但是当与班级的自动测试仪对抗时,它会返回 2 No line found 错误。问课程的工作人员,他们说这可能是因为我试图扫描一条不存在的线,但我尝试打印我所有的扫描并没有发现类似的东西。这就是我的代码中的所有扫描:

Scanner sc = new Scanner(System.in);
    String sentence;
    int choice;

    System.out.println("Please enter a sentence:");
    sentence = sc.nextLine();

    printMenu(); // calls a function to print the menu.

    // gets the require action
    System.out.println("Choose option to execute:");
    choice = sc.nextInt();
    sc.nextLine();

(我尝试使用和不使用最后一个 sc.nextLine)

static void replaceStr(String str)
{
    String oldWord, newWord;
    Scanner in = new Scanner(System.in);

    // get the strings
    System.out.println("String to replace: ");
    oldWord = in.nextLine();
    System.out.println("New String: ");
    newWord = in.nextLine();

    // replace
    str = str.replace(oldWord, newWord);
    System.out.println("The result is: " + str);
    in.close();
}
static void removeNextChars(String str)
{
    Scanner in = new Scanner(System.in);
    String remStr; // to store the string to replace
    String tmpStr = ""; //the string we are going to change.
    int i; // to store the location of indexStr

    // gets the index
    System.out.println("Enter a string: ");
    remStr = in.nextLine();
    i=str.indexOf(remStr);

    in.close(); // bye bye

    if (i < 0)
    {
        System.out.println("The result is: "+str);
        return;
    }

    // Build the new string without the unwanted chars.
    /* code that builds new string */

    str = tmpStr;
    System.out.println("The result is: "+str);
}

知道一条线如何在这里泄漏吗?

4

1 回答 1

4

这是问题所在。您in.close();在多个地方使用(方法中的最后一条语句和replaceStr方法中的中间部分removeNextChars)。当您使用close()方法关闭扫描仪时,它也会关闭您InputStream (System.in)的。该 InputStream 无法在您的程序中重新打开。

public void close() throws IOException --> Closes this input stream and releases any system resources associated with this stream. The general contract of close is that it closes the input stream. A closed stream cannot perform input operations and **cannot be reopened.**

扫描仪关闭后的任何读取尝试都将导致异常 NoSuchElementException。

请在程序完成后关闭扫描仪一次。

编辑:扫描仪关闭/使用:

在你的主要功能中:

   Scanner sc = new Scanner(System.in);
   ....
   .....
   replaceStr(Scanner sc, String str);
   .....
   ....
   removeNextChars(Scanner sc ,String str);
   ....
   ....
   //In the end
   sc.close();


static void replaceStr(Scanner in, String str){
  //All the code without scanner instantiation and closing
  ...
}

static void removeNextChars(Scanner in, String str){
  //All the code without scanner instantiation and closing
  ...
}

你应该一切都好。

于 2012-11-04T07:02:13.053 回答