3

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.

ionesi cristi
  • 125
  • 2
  • 8

2 Answers2

2

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);

Darshan Mehta
  • 30,102
  • 11
  • 68
  • 102
0

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.

Community
  • 1
  • 1
Mick Mnemonic
  • 7,808
  • 2
  • 26
  • 30