我一直在为一个小型项目上课,它运行完美而没有问题但是当与该类的自动测试仪进行对比时,它会返回2找不到行错误。询问课程的工作人员,他们说这可能是因为我试图扫描一条线,当时不存在,但我尝试打印所有扫描并没有发现类似的东西。 这就是我在代码中的所有扫描:
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);
}
知道线路如何泄漏吗?
答案 0 :(得分:4)
这是问题所在。您在多个位置使用in.close();
(replaceStr
方法中的最后一个语句以及removeNextChars
方法中的中间位置)。当您使用close()
方法关闭scnaner时,它也会关闭您的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
...
}
你应该都很好。