Gaurav Kabra
Gaurav Kabra

Reputation: 119

Java - Display Windows -1252 Characters in Eclipse

I am trying to display some Windows-1252 characters by taking their numeric equivalent as input from the user in Java (using Eclipse). I am expecting the character to be displayed as in the link: https://www.w3schools.com/charsets/ref_html_ansi.asp

I tried with numeric values 152 and 149 but they are displayed as question marks in Eclipse console. My code in Eclipse:

import java.io.IOException;
import java.util.Scanner;
public class Encoding_CP1252 {

    public static void main(String[] args) throws IOException {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter a number:");
        int a = in.nextInt();   
        System.out.println("You Entered: " +a);
        char b = (char) a;
        System.out.println("Windows-1252 equivalent is: "+b);
    }
}

I even tried to tweak the Eclipse configuration in Run--> Run Configuration --> Common tab --> Encoding set to 'Default -inherited (Cp1252)' but still the same result.

Upvotes: 0

Views: 664

Answers (1)

howlger
howlger

Reputation: 34275

The char data type [...] are based on the original Unicode specification, which defined characters as fixed-width 16-bit entities.

Because of this char b = (char) a; does not work and you have to use new String(byte[] bytes, String charsetName) instead:

...
byte[] b = {(byte) a};
System.out.println("Windows-1252 equivalent is: "+ new String(b, "Windows-1252"));

Upvotes: 1

Related Questions