【问题标题】:Is there any way to make this more compact?有没有办法让这个更紧凑?
【发布时间】:2013-11-15 14:37:46
【问题描述】:

我有一个项目,其部分目标是尽可能缩短代码。我已经尽我所能使其尽可能紧凑,但我想知道以下代码是否还有更多快捷方式

public static void read(String[] input) throws IOException {
    for (String s : input) {
        BufferedReader b = new BufferedReader(new FileReader(s)); 
        while (b.ready()) {
            String[] val = b.readLine().split(" ");
            for (String c : val) System.out.println(c);
        } 
        b.close();
    }   
}

【问题讨论】:

  • "compact" 是相对的。您可以将它们全部放在一行上,但它仍然是相同的代码。例如,IMO,为了清楚起见,正确使用花括号和 sysout 在它自己的行上会更好地使用 for 循环。
  • 只是为了跟进 MadConan 所说的,我会说保持可读性并牺牲一点紧凑性,而不是压缩到极端并使其难以维护和阅读。关于内部 for 循环,我也同意;要么是花括号,要么将System.out.println 行向下推并缩进一个。坦率地说,否则在我看来还不错。
  • 通常我会一直使用花括号,而不是将所有内容都放在代码中的同一行。这里的挑战是尽可能减少线条,这就是我这样做的原因,但感谢您的反馈。我同意在任何其他正常情况下,正确的格式始终是最好的方法。谢谢
  • 是的。将read 方法命名为reainput 参数inpu
  • challenge here is to have the minimal lines possible 有新行的条件吗?就像每个;{ 之后应该有新的行标记?如果没有,您可以删除代码中的每个新行标记并只获得一行...

标签: java shorthand


【解决方案1】:

这取决于您所说的“紧凑”是什么意思。例如,您可以更改

String[] val = b.readLine().split(" ");
for (String c : val) System.out.println(c);

进入

for (String c : b.readLine().split(" ")) System.out.println(c);

或者使用 Scanner 类使用一些不同的方法,这将使您的代码更短且更具可读性。

public static void read(String[] input) throws IOException {
    for (String s : input) {
        Scanner scanner = new Scanner(new File(s));
        while (scanner.hasNext()) 
            System.out.println(scanner.next());
        scanner.close();
    }
}

您也可以尝试这种方式(基于 Christian Fries 回答的概念)

public static void read(String[] input) throws IOException {
    for (String s : input) 
        System.out.println(new Scanner(new File(s)).useDelimiter("\\Z").next().replace(' ', '\n'));
}

如您所见,这不会让您使用close 扫描器,但由于File 资源不是Closable,您不必调用它的close 方法,因此这种方法看起来很安全。

【讨论】:

  • 非常感谢。很确定它就像我现在要得到的那样“紧凑”
  • 最后一个很酷。第二个是(带有Scanner和hasNext)是最漂亮的一个:紧凑可读。
【解决方案2】:

不要使用split(" "),而是使用for循环将结果数组的每个元素打印在您可能使用的一行上

System.out.println(b.readLine.replace(' ','\n'));

那是

public static void read(String[] input) throws IOException {
    for (String s : input) {
        BufferedReader b = new BufferedReader(new FileReader(s)); 
        while (b.ready()) System.out.println(b.readLine.replace(' ','\n'));
        b.close();
    }   
}

【讨论】:

    猜你喜欢
    • 2021-12-21
    • 1970-01-01
    • 2015-08-13
    • 2011-06-28
    • 2020-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多