【问题标题】:Search string in file and return next line (in Java)在文件中搜索字符串并返回下一行(在 Java 中)
【发布时间】:2013-02-23 20:00:29
【问题描述】:

正如我的标题所说。我需要在文件中搜索字符串。找到后,我需要下一行。 是这样的文件:

你好

世界

当找到“hello”时,需要返回“world”。

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);
    }
  }
}

它会读取文件,但找不到单词“hello”。

【问题讨论】:

标签: java string file string-comparison


【解决方案1】:
if (line == "hello") {

应该是

if ("hello".equals(line)) {

你必须使用 equals() 方法来检查两个字符串对象是否相等。 == 运算符在 String(和所有对象)的情况下仅检查两个引用变量是否引用同一个对象。

【讨论】:

    【解决方案2】:
    if (line == "hello")
    

    应该改为

    if (line.contains("hello"))
    

    【讨论】:

      【解决方案3】:

      而不是使用== 运算符来比较两个字符串使用 if(line.compareTo("hello") == 0)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-11-28
        • 1970-01-01
        • 1970-01-01
        • 2011-01-18
        • 2019-01-28
        • 2012-09-09
        • 2012-03-06
        相关资源
        最近更新 更多