如何正确书写“ \”字符

时间:2019-07-04 19:20:20

标签: java

我正在寻找键入“ \”字符的正确方法,以免出现“非法转义字符”错误

美好的一天,最近我开始使用Java,参加了在线基础课程,并且在我的一个练习代码中,我意识到键盘上键入的“ \”不是正确的转义字符,因此我的代码运行“非法转义”字符串文字中的字符”错误。有什么建议如何正确键入它或如何用正确的字符替换系统中的字符? 这是带有不正确字符的代码:

public class WellFormed {
public static void main(String[] arga) {
    System.out.println("A well-formed Java program has");
    System.out.println("a main method with \{ and \}");
    System.out.println("braces.");
    System.out.println();
    System.out.println("A System.out.println statement");
    System.out.println("has \( and \) and usually a");
    System.out.println("String that starts and ends");
    System.out.println("with a \" character");
    System.out.println("\(but we type \\" instead!");
    }
}

3 个答案:

答案 0 :(得分:1)

"\\"而不是"\"。由于\是转义字符,因此您需要第二个字符来显式地告诉您想要字符\而不只是转义。

答案 1 :(得分:1)

由于不需要'('和'{'的转义,因此给出了非法的景深字符。

    System.out.println("A well-formed Java program has");
    System.out.println("a main method with { and }");
    System.out.println("braces.");
    System.out.println();
    System.out.println("A System.out.println statement");
    System.out.println("has ( and ) and usually a");
    System.out.println("String that starts and ends");
    System.out.println("with a \" character");
    System.out.println("(but we type \\\" instead!");

上面的代码可以编译并按预期工作。

可用作转义序列的字符是:

\t  Insert a tab in the text at this point.
\b  Insert a backspace in the text at this point.
\n  Insert a newline in the text at this point.
\r  Insert a carriage return in the text at this point.
\f  Insert a formfeed in the text at this point.
\'  Insert a single quote character in the text at this point.
\"  Insert a double quote character in the text at this point.
\\  Insert a backslash character in the text at this point.

您可以在此处找到Java 8的文档:https://docs.oracle.com/javase/tutorial/java/data/characters.html

答案 2 :(得分:-1)

public class WellFormed {
public static void main(String[] arga) {
    System.out.println("A well-formed Java program has");
    System.out.println("a main method with \\{ and \\}");
    System.out.println("braces.");
    System.out.println();
    System.out.println("A System.out.println statement");
    System.out.println("has \\( and \\) and usually a");
    System.out.println("String that starts and ends");
    System.out.println("with a \" character");
    System.out.println("(but we type \\\" instead!");
}
}