【发布时间】:2021-11-03 22:07:53
【问题描述】:
此程序在文件中搜索给定条目。我认为我的主要打印声明是不正确的。当我运行命令提示符时,我的程序会打印出“未找到物品猫!”即使“cat”出现在程序检查的列表中。这是列表: 猫 鼠 增值税 垫 蝙蝠 帽子 扎特 拍 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
}
}
【问题讨论】:
标签: java search sequential