gpt4 book ai didi

java - 扫描线是否逃逸?

转载 作者:行者123 更新时间:2023-12-01 18:58:24 32 4
gpt4 key购买 nike

我一直在为类(class)做一个小项目,它运行完美,没有任何问题,但是当与类(class)的自动测试器进行比较时,它返回 2 No line found 错误。询问类(class)的工作人员,他们说这可能是因为我试图扫描一条不存在的线,但我尝试打印所有扫描结果,但没有发现类似的东西。这就是我的代码中的所有扫描:

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);
}

你知道线路是如何泄漏的吗?

最佳答案

问题就在这里。您在多个位置使用 in.close();(replaceStr 方法中的最后一个语句以及 removeNextChars 方法的中间语句)。当您使用 close() 方法关闭扫描仪时,它也会关闭您的 InputStream (System.in) 。该 InputStream 无法在您的程序中重新打开。

public void close() throws IOException --> 关闭此输入流并释放与此流关联的所有系统资源。 close 的一般约定是关闭输入流。关闭的流无法执行输入操作,并且**无法重新打开。**

扫描仪关闭后的任何读取尝试都将导致异常 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
...
}

你应该一切都好。

关于java - 扫描线是否逃逸?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13216655/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com