我有我的名字4,票據,戴夫,邁克創建一個文件names.txt行號名稱from.txt文件,andjim我不能顯示在控制檯
我可以輸入文件名稱,我可以輸入名稱進行搜索,例如上面的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();
}
}
爲什麼你要比較字符串「friendName」而不是字符串變量friendName。 –