【问题标题】:Where do I place the return of a function in JAVA?在 JAVA 中,函数的返回值应该放在哪里?
【发布时间】:2021-03-27 23:41:03
【问题描述】:

我试图弄清楚如何在 JAVA 中创建一个函数,该函数每行搜索一个文档行: 首先我初始化文件和读取器,然后将每一行转换为 ArrayList 中的字符串;之后,我尝试根据字符串检查 ArrayList,然后将 ArrayList 的位置作为字符串返回。

例如,我有一个包含以下内容的文本: 1 - 在彩虹的某个地方 2 - 很高。

转换为 ArrayList,如果随后搜索:“Somewhere”;那么它应该返回句子“Somewhere over the rainbow”;

这是我尝试过的代码;但它一直返回“null”;

String FReadUtilString(String line) {
    File file = new File(filepath);
    ArrayList<String> lineReader = new ArrayList<String>();
    System.out.println();


    try {
        Scanner sc = new Scanner(file);
        String outputReader;

        while (sc.hasNextLine()) {
            lineReader.add(sc.nextLine());
        }
        sc.close();

        for(int count = 0; count < lineReader.size(); count++) {
            if(lineReader.get(count).contains(line)){outputReader = lineReader.get(count);}
        }
    } catch (Exception linereadeline) {
        System.out.println(linereadeline);
    }
    return outputReader;
}

【问题讨论】:

  • outputReader 没有做任何事情,因为您的程序是为了找到第一个匹配项。在这种情况下,您应该简单地 return lineReader.get(count); 而不是将其保存在 outputReader 中。
  • 你试过调试你的代码吗?检查您的数组是否包含预期的字符串?
  • 你能澄清一下吗?我是否只需将返回编辑为 'LineReader.get(count);或者我该怎么办?
  • 顺便说一句。请使用一些合理的变量名。 lineReader 不是 Reader,它是一个包含行的数组。 outputReader 也不是读者,它是一些“结果”。
  • @Jai or OP 有一个名为 outputReader 的隐藏类变量 null 因为实际分配了值的局部变量超出了范围。变量名可能更有意义。为什么命名 Exception linereadeline 例如?为什么要在每次方法调用时重新读取文件?等等。

标签: java arraylist return


【解决方案1】:

我稍微重构了你的代码,但我保留了你的逻辑,它应该对你有用:

String FReadUtilString(String line, String fileName){
    File file = new File(fileName);
    List<String> lineReader = new ArrayList<>();
    String outputReader =  "";
  
    try (Scanner sc = new Scanner(file))
    {
      while (sc.hasNextLine()) {
        lineReader.add(sc.nextLine());
      }
  
      for (int count = 0; count < lineReader.size(); count++){
        if (lineReader.get(count).contains(line)){
          outputReader = lineReader.get(count);
        }
      }
    }
  
    catch (Exception linereadeline) {
      System.out.println(linereadeline);
    }

    return outputReader;
  }

注意:我使用 try-with-resource 语句来确保 Scanner 的关闭。

【讨论】:

  • List&lt;String&gt; lineReader = java.nio.file.Files.readAllLines(file.toPath());
  • 请添加一些解释初始代码出了什么问题。 OP 只是在学习,所以知道它为什么不起作用真的很有价值。 (查看 Elliott Frisch 对问题本身的评论)
【解决方案2】:

更简洁的版本:

String fReadUtilString(String line, String fileName) {
    try (Stream<String> lines = Files.lines(Paths.get(fileName))) {
        return lines.filter(l -> l.contains(line)).findFirst();
    }
    catch (Exception linereadeline) {
        System.out.println(linereadeline);  // or just let the exception propagate
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-15
    • 2011-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-18
    • 2012-02-17
    相关资源
    最近更新 更多