我有一个我用4个名字创建的Names.txt文件,bill,dave,mike和jim
我可以输入文件名,我可以输入要搜索的名称,例如上面的dave,然后控制台应该返回“dave出现在Names.txt的第2行”。相反,它返回“dave不存在”,如果它不是四个名称之一,那将是正确的。我在下面的while循环中犯了什么错误?
public class names {
public static void main(String[] args) throws IOException {
String friendName; // Friend's name
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
// Get the filename.
System.out.print("Enter the filename: ");
String filename = keyboard.nextLine();
// Open the file.
File file = new File(filename);
Scanner inputFile = new Scanner(file);
// Get the name of a friend.
System.out.print("Enter name to search: ");
friendName = keyboard.nextLine().toLowerCase();
int lineNumber = 1;
while (inputFile.hasNextLine()) {
if ("friendName".equals(inputFile.nextLine().trim())) {
// found
String line = inputFile.nextLine();
System.out.println("friendName" + " appears on line " + lineNumber + " of Names.txt");
lineNumber++;
//break;
} else {
// not found
System.out.println(friendName + " does not exist. ");
break;
}
}
// Close the file.
inputFile.close();
}
}
答案 0 :(得分:1)
从friendName
删除引号并使用您从文件中读取的实际变量:
int lineNumber = 1;
booelan found = false;
while (inputFile.hasNextLine()) {
String nextLine = inputFile.nextLine().trim();
if (friendName.equals(nextLine)) {
// found
found = true;
break; // name is found, no point in searching any further
}
lineNumber++; // always increment the line number
}
if (found) {
System.out.println(friendName + " appears on line " + lineNumber + " of Names.txt");
}
else {
System.out.println(friendName + " does not exist. ");
}
我也改变了你使用Scanner
的方式。在原始代码中,如果与朋友姓名匹配,则会调用Scanner.nextLine()
两次。这会导致扫描仪推进两条线,这不是你想要的。
答案 1 :(得分:0)
package com.stackoverflow;
import java.io.*;
import java.util.*;
public class Names
{
public static void main(String[]args) throws IOException
{
String friendName; // Friend's name
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
// Get the filename.
System.out.print("Enter the filename: ");
String filename = keyboard.nextLine();
// Open the file.
File file = new File(filename);
Scanner inputFile = new Scanner(file);
// Get the name of a friend.
System.out.print("Enter name to search: ");
friendName = keyboard.nextLine().toLowerCase();
int lineNumber = 0;
Boolean isFound = false;
while(inputFile.hasNextLine()){
lineNumber++;
String line = inputFile.nextLine();
if(line.trim().contains(friendName)){
System.out.println(friendName + " appears on line " + lineNumber + " of Names.txt");
}
}
if(!isFound){
System.out.println("given friend name "+friendName+" not exists in the file");
}
// Close the file.
inputFile.close();
} }