我在開始編程類,似乎有搜索文本文件的主要問題。我的代碼應該做的,基於分配:掃描儀只搜索.txt文件的第一行
- 接受輸入,在這種情況下,名稱和輸入放入一個.txt文件
- 允許用戶搜索姓名,或一部分名稱,並返回所有具有匹配文本的行。
我已經完成了賦值的輸入部分,並且在完成檢索部分的邊緣,但是我的代碼只搜索.txt文件的第一行。我可以打印出.txt文件的所有行,並且如果我在.txt文件的第1行中搜索名稱,它將正確打印行。我的問題是當我正在尋找,是不是在1號線下方的名稱是我的代碼:
System.out.println ("Would you like to retrieve names from your index? (YES/NO)");
try
{
retrieve=input.readLine();
}
catch (IOException E)
{
System.out.println(E);
}
}
if (choice == 2 && retrieve.equalsIgnoreCase("YES") || retrieve.equalsIgnoreCase("Y"))
{
while (retrieve2.equalsIgnoreCase("YES") || retrieve2.equalsIgnoreCase("Y"))
{
FileReader reader = new FileReader("Name_Index.txt");
BufferedReader bufferedReader = new BufferedReader(reader);
String line = bufferedReader.readLine();
System.out.println ("Enter a string of characters in which to search by or enter \"all names\" f$
search_term = gatherInput();
System.out.println("Search results include: ");
ArrayList<String> list = new ArrayList<String>();
Scanner inFile = new Scanner (new File("Name_Index.txt"));
inFile.useDelimiter(",");
while (inFile.hasNextLine())
{
list.add(inFile.nextLine());
}
Collections.sort(list);
if (search_term.equalsIgnoreCase("all names"))
{
for (String temp : list)
{
System.out.println(temp);
}
}
else if (line.toLowerCase().contains(search_term.toLowerCase()))
{
System.out.println(line);
bufferedReader.close();
}
System.out.println("End!");
System.out.println ("Would you like to retrieve names from your index? (YES/NO)");
try
{
retrieve2=input.readLine();
}
catch (IOException E)
{
System.out.println(E);
}
}
System.out.println("Thank you, come again!");
}
}
public static String gatherInput()
{
Scanner scan = new Scanner(System.in);
String user_input = scan.nextLine();
return user_input;
}
}
我試圖擴大而(inFile.hasNextLine())迴路包括第二屆「如果「語句,但是會爲」所有名稱「搜索創建一個問題 - 它會多次返回整個列表(無論文件中有多少行)。我甚至嘗試在第二個「if」語句中創建另一個while(inFile.hasNextLine())循環,並且結果沒有差異。
在這一點上,我非常沮喪,因爲我已經在這個代碼上工作了一個多星期,並且沒有任何幫助地檢查了我所有的筆記和演講錄音。任何有識之士將不勝感激。
可以重新格式化您的代碼,以便縮進是明確的?另外,在你的第一個catch塊之後你有一個神祕的'}'......它關閉了什麼? – Linus
「所有的名字」是否給你一個正確的輸出?你還沒有使用'BufferedReader'對象。 – Blip
@Blip是的。 「全名」請求返回完整列表。儘管如此。 – DeaLunae