我的IF条件存在轻微问题。此方法读取用户输入并扫描文本文件以查找输入的文本。这样可行。如果找不到输入,我想执行我的Writer方法。我的问题就在于此。我似乎无法返回找到的行并退出程序。相反,我返回一个找到的行,然后调用编写器方法,这不是我想要做的。
public static void parseFile(String s) throws FileNotFoundException {
File file = new File("data.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
final String lineFromFile = scanner.nextLine();
if (lineFromFile.contains(s)) {
// a match!
System.out.println(lineFromFile);
}
else{
Writer();
}
}
}
这是我的作家方法。
public static void Writer() {
Scanner Keyboard = new Scanner(System.in);
Scanner input = new Scanner(System.in);
File file = new File("data.txt");
try (BufferedWriter wr = new BufferedWriter(new FileWriter(
file.getAbsoluteFile(), true))) { // Creates a writer object
// called wr
// file.getabsolutefile
// takes the filename and
// keeps on storing the old
System.out
.println("I cannot find this line... Enter new line"); // data
while ((Keyboard.hasNext())) {
String lines = Keyboard.nextLine();
System.out.print(" is this correct ? ");
String go = input.nextLine();
if (go.equals("no")) {
System.out.println("enter line again");
lines = Keyboard.nextLine();
System.out.print(" is this correct ? ");
go = input.nextLine();
}
if (go.equals("yes")) {
wr.write(lines);
wr.write("\n");
wr.newLine();
wr.close();
}
System.out.println("Thankk you");
break;
}
} catch (IOException e) {
System.out.println(" cannot write to file " + file.toString());
}
}
答案 0 :(得分:0)
使用标记来标识是否找到了输入s
,请尝试这种方式,
public static void parseFile(String s) throws FileNotFoundException {
File file = new File("data.txt");
Scanner scanner = new Scanner(file);
int flag_found=0;
while (scanner.hasNextLine()) {
final String lineFromFile = scanner.nextLine();
if (lineFromFile.contains(s)) {
// a match!
System.out.println(lineFromFile);
flag_found = 1;//Input is found
}
}
if(flag_found==0){// input is not found in the txt file so flag_found remains 0
Writer();
}
}
答案 1 :(得分:0)
我会重新安排你的程序,以便。
static final
全局。这通常是一个糟糕的选择,但在你的情况下,你正在包装一个全局字段。break;
或return;
来打破循环。答案 2 :(得分:0)
您遇到程序正在调用Writer
- 方法的原因是,循环将继续执行,直到文本文件结束。您可以使用break
退出while
- 循环:
public static void parseFile(String s) throws FileNotFoundException {
File file = new File("data.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
final String lineFromFile = scanner.nextLine();
if (lineFromFile.contains(s)) {
// a match!
System.out.println(lineFromFile);
break; // <--- break out of the loop when a match is found.
}
else
{
Writer();
}
}
}
答案 3 :(得分:0)
您似乎可以将方法编写为:
public static String parseFile(String s) throws FileNotFoundException {
File file = new File("data.txt");
boolean inputFound = false;
Scanner scanner = new Scanner(file);
String lineFromFile;
while (scanner.hasNextLine()) {
lineFromFile = scanner.nextLine();
if (lineFromFile.contains(s)) {
// a match!
inputFound = true;
break;
}
}
if(!inputFound) {
writer(); //camel case should be used.
return ""; //empty string
} else {
return lineFromFile;
}
}
在旁注方法名称应该是驼峰式的。此外,您不需要每次循环创建新的String lineFromFile
。