java - txt文件的Java顺序搜索
问题描述
该程序在文件中搜索给定条目。我认为我的主要打印声明是不正确的。当我运行命令提示符时,我的程序打印出“未找到物品猫!” 即使“cat”出现在程序检查的列表中。清单如下: CAT RAT VAT MAT BAT HAT ZAT PAT SAT TAT
这是我的程序:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class SequentialSearchFile {
public static void main(String args[])
{
// String to contain filename
String fileName = "";
// String to contain search item;
String searchItem;
Scanner s = new Scanner (System.in);
// If there is one command-line parameter
if (args.length == 1 )
{
fileName = args[0]; // assume that it is the filename
System.out.print("Please enter search item: ");
searchItem = s.nextLine();
}
// If there are two command-line parameters
else if (args.length == 2)
{
fileName = args[0]; // take them as the filename
searchItem = args[1]; // and as the search item
}
else {
System.out.print("Please enter file name: ");// no command line parameters?
fileName = s.nextLine(); // prompt user for both
System.out.print("Please enter search item: ");
searchItem = s.nextLine();
}
searchItem = searchItem.trim(); // trim any extra spaces from search item
System.out.println("Searching file" + fileName + "...");
System.out.println("Item " + searchItem + " was " +
(sequentialSearch(fileName, searchItem) ?"" : "NOT ") + "found!");
}
// method opens file and searches the contents
public static boolean sequentialSearch (String fileName, String searchItem) {
boolean result = false; // default response is not found
try {
Scanner f = new Scanner(new File(fileName)); // get a connection to the file
String fileItem;
while(f.hasNext())
{
fileItem = f.nextLine(); // check each entry against the search item
if(searchItem.equalsIgnoreCase(fileName))
{
result = true; // if found, set result to true
break; // and break out of the while loop
}
}
}
catch(FileNotFoundException e) { // if the file wasn't there,
System.out.println(e.toString()); // show the exception text
System.exit(0); // and exit
}
return result; // return the result
}
}
解决方案
实施有几个问题。
首先,您使用 (这是正确的!)检查下一个字符串,hasNext()
然后使用 读取整行nextLine()
而不是使用next()
.
其次,在您比较searchItem
的每次迭代中,fileName
而不是fileItem
您从文件中读取的:
Scanner f = new Scanner(new File(fileName));
String fileItem;
while(f.hasNext()) {
fileItem = f.next(); // A single item is read with next(), not nextLine()
if(searchItem.equalsIgnoreCase(fileItme)) { // searchItem is compare to fileItem
result = true;
break;
}
}
注意:
为简洁起见,答案中省略了错误处理和资源管理,但当然应该出现在您的实际代码中。
推荐阅读
- php - 显示来自 Woocommerce 购物车项目中自定义字段的自定义延期交货文本
- javascript - 带有共享案例的 Javascript switch 语句
- sas - SAS图形/地图图例格式
- javascript - 按键分组对象数组并将分组结果与日期数组进行比较
- javascript - 带有布尔值的 Object.assign
- javascript - 如何在 w3 代码中添加 2 个以上的幻灯片?
- ios - 如何在 tableview 方法之外获取 tableview [section]?
- linux - 当目录名称包含空格且目录具有特定文件扩展名时,如何遍历目录并将它们移动到另一个位置
- windows - 对文件夹中的图片进行排序
- jhipster - 如何为基于令牌的身份验证禁用 csrf 并为浏览器启用它?