【问题标题】:How to return inside a while loop?如何在while循环内返回?
【发布时间】:2018-01-14 21:01:36
【问题描述】:

我想要一个方法来返回在 while 循环中出现的值。我的代码代表读取一个 txt 文件,我在其中逐行读取,我的目标是每次找到一行时都返回,但一遍又一遍地向我显示相同的数字。

public String getInputsTxtFromConsole() {
    String line = "";

    //read inputs file
    try {
        Scanner scanner = new Scanner(inputFile);

        //read the file line by line
        int lineNum = 0;
        while (scanner.hasNextLine()) {
            line = scanner.nextLine();
            lineNum++;

            //Return statement does not work here
        }
    } catch (FileNotFoundException e) {

    }

    return "";
}

【问题讨论】:

  • 你能分享一个示例输入文件和你试图得到的结果吗?这会让问题更清楚。
  • 输入是字符串,如:96464444; 96464644;94646464 等
  • 我只想在 while 循环中单独返回每个数字
  • return 语句 exits 函数,它不会像 python 中的 yield 那样一直给你所有的值,创建一个你想要的行数组然后返回数组。
  • 但我想单独返回,而不是同时返回

标签: java while-loop


【解决方案1】:

正如 Nick A 所说,return 的使用有两种用途:返回函数的值和退出函数。我需要所有生成的值,例如,

  • 调用使用新值的方法:

    line = scanner.nextLine();
            lineNum++;
            //Return statement does not work here
            ConsumerMethod(line);
    }
    
  • 存储在全局变量中,如 ArrayList、String[]、...

  • 打印 System.out.println(line)。
  • ...

但是你不能返回一个值并期望函数继续工作。

【讨论】:

    【解决方案2】:

    正如我提到的,将相同的扫描仪作为参数传递给读取一行并返回该行的方法。您可能想要定义它在没有剩余行时如何响应。

    public String getInputsTxtFromConsole(Scanner scanner) {
        try {
            if (scanner.hasNextLine()) {
                return scanner.nextLine();
            }
        } catch (FileNotFoundException e) {
    
        }
        return null;
    }
    

    我还建议使用不同的类来读取文件。 BufferedReader 将是一种更好的方法。

       BufferedReader in = new BufferedReader(new FileReader (file));
    ... // in your method
        return in.readLine(); //return null if the end of the stream has been reached
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-09
      • 2015-02-24
      • 2021-05-13
      • 2016-05-22
      • 2019-05-08
      • 2016-10-28
      • 1970-01-01
      • 2015-11-17
      相关资源
      最近更新 更多