Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Special characters are input wrongly

I'm having a queer issue. I have this code in Java:

Scanner keyboard = new Scanner(System.in);
System.out.print("Enter word: ");
String word = keyboard.nextLine();
System.out.println(word);

However, for special characters, the scanner class seems to be going wrong. For example, if I type in ħabel I get ħabel printed. Eclipse's console output is set as UTF-8, sure of that, so I think it's coming from the input. I haven't found any encoding options in the Scanner class really and funnily googling about didn't give solutions neither. How could this be solved?

Thanks!

like image 854
Krt_Malta Avatar asked Sep 10 '26 03:09

Krt_Malta


2 Answers

When you set up a Scanner on a bare InputStream, it reads using the default charset (which for you seems to be ASCII). If you want to specify the charset, do this:

Scanner keyboard = new Scanner(new InputStreamReader(
                    System.in, Charset.forName("UTF-8")));
like image 112
Russell Zahniser Avatar answered Sep 11 '26 15:09

Russell Zahniser


I believe Russel answer is correct, but it seems that your input charset is not UTF-8 Try this: Scanner s= new Scanner(new InputStreamReader(System.in,Charset.defaultCharset()));

like image 23
wmz Avatar answered Sep 11 '26 17:09

wmz