简体   繁体   中英

using scanner input escape sequence not working

Below is the code in which i ask user to enter string and also i give a value to another string .

public static void main(String[] args) throws Exception {

Scanner sc=new Scanner(System.in);
String s=sc.next();  //input="C:\\slp.txt" or C:\\slp.txt
String j="C:\\slp.txt";
System.out.println(s);
System.out.println(j);
}

Output for s= "C:\\\\slp.txt" or C:\\\\slp.txt

Output for j= C:\\slp.txt

why jvm treats as a backslash escape sequence in case of j and not in case of s?

When you hard code a string in code, say you specify,

String s = "hey \";

This won't compile/work because certain special characters like slash() and doublequote(") have special meaning in string. Like slash is used to escape a character where as doublequote is used to start and end a string. Hence you need to escape them, otherwise parser will fail to parse resulting in compilation error. So if you want a literal value of \\ you need to escape it and write it as \\\\ while specifying it in the code.

But when you take input from user at runtime, then there you don't have to worry about escaping characters because entered input doesn't have to be parsed for correctness of string and instead user can enter whatever they want and indeed when you enter \\\\, then it is JVM's responsibility to preserve user's input as it was entered by user, hence internally these two slashes are actually represented by four slashes \\\\\\\\. Try debugging and see the value of string inputted by user.

Hope this explains. Let me know if you still have any doubt.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM