问题
I want to print n Greek characters in Java starting from alpha (whitch has the "\u03B1" code).This is what I had in mind:
String T = "";
for(int i = 0,aux = 0;i<n;i++)
{
aux = '\u03B1' + i;
T +=Character.toString((char)aux);
}
System.out.println(T);
But it prints n question marks instead.
Let's say n=3,on the output i get "???".
I thought that maybe my method is wrong but then again if I try something like this:
System.out.println("\u03B1\u03B2\u03B3");
I get the same output:"???"
Why do I get this output instead of the desired characters and how can I print them like I want to?
Note:I use IntelliJ as IDE and my OS is Windows 10.
回答1:
I think it has something to do with default Charset set in the system. We can use the following line to print the default charset at runtime:
System.out.println(Charset.defaultCharset());
May be your system doesn't have UTF-8 set by default, in this case, we can convert the string to UTF-8 before printing, e.g.:
System.out.println(new String(T.getBytes(),"UTF-8"));
This prints alpha, beta and gamma to console.
P.S. don't know if it's a typo but T +=Character.toString((char)aux2);
needs to be changed to T +=Character.toString((char)aux);
回答2:
You get the invalid character output because the console output of your IDE is (probably) set to Windows default charset encoding, CP-1252, but Java natively uses Unicode encoding.
To fix the problem, you should set the charset encoding of your IDE's console output to UTF-8, e.g. by using the instructions from this post.
来源:https://stackoverflow.com/questions/35676915/i-want-to-display-greek-unicode-characters-but-i-get-instead-on-ouput