Problem overview
When using VS Code to write a Java program, I want to use Scanner to obtain the string entered by the keyboard, and find that English and numbers can be obtained normally, but when you enter Chinese, Scanner returns a string of garbled characters (sometimes a few spaces). The strange thing is that the same code can be put into Eclipse to get Chinese, so it is basically a problem with the settings of VS Code itself.
Solution
Let's first observe what VS Code does when you debug the program
You can see that it loads a script file called launcher, point the mouse and press Ctrl + left mouse button to open it, you
can find that VS Code has changed the code page to UTF-8 for better compatibility (the result will result in Chinese garbled characters - - )
Here 65001 represents UTF-8, modify it to 936 to indicate that GBK storage is off. But it’s not over yet. When I run the program, I find that the Chinese characters obtained by the Scanner are still garbled. Let’s take a look at the string of information when VS Code is debugging.
This sentence shows that when you debug the program, the Java virtual machine starts, and the default character set is set to UTF-8, which will still cause garbled characters. To modify this, you need to open the project debugging settings file launch.json of VS Code, located in the project resource management directory of the device.
Open it and find the code block below,
add a line below "encoding": "GBK" Don't forget to add a comma after "mainClass": "${file}" above.
Run it again and find that it has changed.
Finally, change the default encoding of the VS Code file to GBK. The location is [File] → [Preferences],
search for [Encoding] in the settings, and then set the following item to GBK. But
now the Scanner can read Chinese correctly