uranibaba
uranibaba

Reputation: 752

Special characters not working with StringBuilder.append(String)

Part of my code:

Scanner in = new Scanner(System.in);
String s = in.nextLine();
StringBuilder sb = new StringBuilder(s.length());
sb.append(s); 

If add

System.out.println(sb);

on line 5, it will output � if I enter special character (åäö) at line 4:

String s = in.nextLine();

Why is it behaving like this? Should I use something else to get input from the user?

EDIT: It will output "åäö" corretly if I just append "åäö" to a StringBuild and print it with System.out.println(sb); (where sb is the StringBuilder).

EDIT 2: I am using NetBenas IDE 8.0

EDIT 3: The problem does not seem to be the encoding.

Scanner sc = new Scanner(System.in,"utf-8");

Still gives the same result.

Upvotes: 1

Views: 4221

Answers (2)

sol4me
sol4me

Reputation: 15698

Strings are always encoded as UTF-16 in java. Set the encoding of your console properly. If you are using some IDE then just google on how to set UTF-8 encoding for console

Upvotes: 0

Nikola Dimitrovski
Nikola Dimitrovski

Reputation: 708

What IDE are you using. Try set the console to print UTF-8 chars. If you are using Eclipse go in Run Configurations --> select your Run Configuration --> Under Common tab change the encoding

Upvotes: 1

Related Questions