gpt4 book ai didi

java - 更新文本文件中的旧行

转载 作者:行者123 更新时间:2023-12-02 04:41:46 28 4
gpt4 key购买 nike

好的,我在尝试更新文本文件中的一行或句子时遇到问题。

我的程序的工作方式是这样的:如果用户输入一个问题,程序会在文本文件中搜索该问题(假设是 n)。问题的答案将在以下行(n + 1)中。我的问题是尝试将以下行(n + 1)更新为用户输入的一些新行。

当我尝试更新文本文件中的行时,我不断收到线程“main”java.util.NoSuchElementException:未找到行异常。我的 removedata() 是我尝试更新文本行的地方。

这是我的代码

public static void removedata(String s) throws IOException {

File f = new File("data.txt");
File f1 = new File("data2.txt");
BufferedReader input = new BufferedReader(new InputStreamReader(
System.in));
BufferedReader br = new BufferedReader(new FileReader(f));
PrintWriter pr = new PrintWriter(f1);
String line;

while ((line = br.readLine()) != null) {
if (line.contains(s)) {

System.out.println("Enter new Text :");
String newText = input.readLine();
line = newText;
System.out.println("Thank you, Have a good Day!");

}

pr.println(line);
}
br.close();
pr.close();
input.close();
Files.move(f1.toPath(), f.toPath(), StandardCopyOption.REPLACE_EXISTING);

}

public static void parseFile(String s) throws IOException {

File file = new File("data.txt");
Scanner scanner = new Scanner(file);
Scanner forget = new Scanner(System.in);
while (scanner.hasNextLine()) {
final String lineFromFile = scanner.nextLine();
if (lineFromFile.contains(s)) {
System.out.println(scanner.nextLine());

System.out
.println(" Would you like to update this information ? ");
String yellow = forget.nextLine();
if (yellow.equals("yes")) {
removedata(scanner.nextLine()); // NoSuchElementException
// error
} else if (yellow.equals("no")) {

System.out.println("Have a good day");
// break;
}

}
}
}

public static void getinput() throws IOException {

Scanner scanner = new Scanner(System.in);
String input = null;
/* End Initialization */
System.out.println("Welcome ");
System.out.println("What would you like to know?");

System.out.print("> ");
input = scanner.nextLine().toLowerCase();
parseFile(input);
}

public static void main(String args[]) throws ParseException, IOException {
/* Initialization */
getinput();

}

我的文本文件是:

           what is the textbook name?
the textbook name is Java
how is the major?
the major is difficult
how much did the shoes cost?
the shoes cost ten dollars

有人可以帮我解决这个问题吗?

最佳答案

parsefileif block 中的代码更改为

String temp = scanner.nextLine();
System.out.println(temp);

System.out
.println(" Would you like to update this information ? ");
String yellow = forget.nextLine();
if (yellow.equals("yes")) {
removedata(temp); // NoSuchElementException
// error
} else if (yellow.equals("no")) {

System.out.println("Have a good day");
// break;
}

要了解其原理的解释,请查看 Nick L. 的回答。

关于java - 更新文本文件中的旧行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30098600/

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