在java中,函数的返回应该放在哪里?

mqxuamgl  于 2021-06-29  发布在  Java
关注(0)|答案(2)|浏览(385)

我试图弄清楚如何在java中创建一个函数,每行搜索一个文档行:首先初始化文件和读取器,然后将每行转换为arraylist中的一个字符串;之后,我尝试对照字符串检查arraylist,然后将arraylist的位置作为字符串返回。
举个例子,我有一个文本,包含:1-彩虹上的某个地方2-向上。
转换为arraylist,如果然后搜索“某处”;然后它应该返回一句“彩虹之上的某处”;
这是我试过的代码;但它一直返回'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;
}
2w3kk1z5

2w3kk1z51#

我对你的代码进行了一点重构,但我保留了你的逻辑,它应该适合你:

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语句来确保关闭扫描仪。

zxlwwiss

zxlwwiss2#

更简洁的版本:

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

相关问题