猿问

如何正确书写“\”字符

我正在寻找键入“\”字符的正确方法,这样我就不会收到“非法转义字符”错误


美好的一天,最近我开始使用 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!");

    }

}


富国沪深
浏览 153回答 3
3回答

拉莫斯之舞

写"\\"而不是"\"。由于\ 是一个转义字符,您需要第二个字符来明确地告诉您想要这个字符\,而不仅仅是转义。

繁星淼淼

它给出了非法转义字符,因为不必转义“(”和“{”。    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

白衣染霜花

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!");}}
随时随地看视频慕课网APP

相关分类

Java
我要回答