英文:
Find line with text in a file
问题
我想要在 options.bldata 中查找是否有写入 firstLaunch=,为此我编写了以下代码:
File file = new File("options.bldata");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line.equals("firstLaunch=")) {
System.out.println("123");
}
}
当它找到一行包含 firstLaunch= 的内容时,它应该打印出 123。但是我不知道为什么即使 firstLaunch= 存在于文件中,它也没有打印出 123。
英文:
I wanted to find out in options.bldata if firstLaunch= was written, for this I wrote the following code:
File file = new File("options.bldata");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line == "firstLaunch=") {
System.out.println("123");
}
}
when it finds a line with firstLaunch= it should print 123, but I don't know why it doesn't print 123 even if firstLaunch= is in the file.
答案1
得分: 2
Operator == 检查两个对象是否指向同一内存位置,而 .equals() 方法评估对象中的值进行比较。
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line.equals("firstLaunch=")) {
System.out.println("123");
}
}
这里有一篇文章提供更多信息。
英文:
Operator == checks if both objects point to the same memory location whereas .equals() evaluates to the comparison of values in the objects.
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line.equals("firstLaunch=")) {
System.out.println("123");
}
}
Here is an article for more information
答案2
得分: 1
代码中有两个错误之处。
- 永远不要使用双等号来比较字符串。你需要使用字符串的
equals()
函数来进行比较。 - 你想要测试的是字符串
firstLaunch=
是否在这一行中,而不是你的行是否等于firstLaunch=
。为此,你可以使用line.contains("firstLaunch=")
。
英文:
There is two wrong thing in the code.
- Never use double equals to compare strings. You need to use the
equals()
function from string to do so - you want to test if the string
firstLaunch=
is in the line, not that your line is equals tofirstLaunch=
. For this, you can useline.contains("firstLaunch=")
答案3
得分: 1
你应该使用 equals()
来比较字符串。或者在你的情况下,使用 contains()
,因为该行可能还有其他内容,不仅仅是你想要查找的部分。
英文:
You should use equals()
to compare strings. Or in your case, contains()
because the line might have other stuff, not just what you want to find
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论