java - 非法文本 block 打开定界符序列,缺少行终止符

标签 java string delimiter java-13

Java 13 来了,所以我开始研究它的新特性,其中之一就是文本 block

我写了一个简单的程序

public final class Example {
    public static void main(String[] args) {
        final String greeting = """Hello
        It's me, Andrew!""";
        System.out.println(greeting);
    }
}

我期待看到

Hello
It's me, Andrew!

我得到的是一个编译错误说

illegal text block open delimiter sequence, missing line terminator

最佳答案

文本 block 的上下文必须从一个新行开始。

public final class Example {
    public static void main(String[] args) {
        final String greeting = """
            Hello
            It's me, Andrew!""";
        System.out.println(greeting);
    }
}

打印

Hello
It's me, Andrew!

摘自 JEP 355: Text Blocks (Preview) :

A text block consists of zero or more content characters, enclosed by opening and closing delimiters.

The opening delimiter is a sequence of three double quote characters (""") followed by zero or more white spaces followed by a line terminator. The content begins at the first character after the line terminator of the opening delimiter.

不过,您不一定非要在内容末尾放置行终止符。

The closing delimiter is a sequence of three double quote characters. The content ends at the last character before the first double quote of the closing delimiter.

final String greeting = """
    Hello
    It's me, Andrew!
    """;

意味着

Hello
It's me, Andrew!
<an empty line here>

我发现它非常不清楚,所以我不得不与社区分享。

关于java - 非法文本 block 打开定界符序列,缺少行终止符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57853217/

相关文章:

java - 访问循环外的 while 循环创建的数组

java - 如何在日语 utf-8 汉字上使用 java 子字符串

java - Java 中正则表达式的问题

c - 程序适用于字符串文字,但不适用于字符串数组

string - 为什么流行的编程语言不使用其他字符来分隔字符串?

java - 如何将带有逗号分隔值的字符串从表拆分为 2 个文本字段?

java - 在Java中测试服务层的void方法

java - 未经授权的 Rovi TV Listings Service Soap 1.2

java - Android TextView 空指针异常

java - 在添加分隔符后在Java中分割字符串