1 java string file string-comparison
正如我的标题所说.我需要在文件中搜索字符串.当它找到时,我需要下一行.这是一个这样的文件:
你好
世界
当找到"你好"时,需要返回"世界".
File file = new File("testfile");
Scanner scanner = null;
try {
scanner = new Scanner(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if (scanner != null) {
String line;
while (scanner.hasNextLine()) {
line = scanner.nextLine();
if (line == "hello") {
line = scanner.nextLine();
System.out.println(line);
}
}
}
Run Code Online (Sandbox Code Playgroud)
它读取文件,但没有找到"你好"这个词.
if (line == "hello") {
Run Code Online (Sandbox Code Playgroud)
应该
if ("hello".equals(line)) {
Run Code Online (Sandbox Code Playgroud)
您必须使用equals()方法来检查两个字符串对象是否相等.==String(和所有对象)的运算符只检查两个引用变量是否引用同一个对象.