简体   繁体   中英

Char to Int Conversion Java

public static void main (String[] args)
{
    char x = 'x';
    char w = x-1;
    System.out.println(w);
}

Whenever I try to run the following code, I got a loss of precision. The compiler tells me that the line char w = x-1 doesn't seem to work. How can I make the char value equal w ?

You need to re-cast to char as you converted to int

char x = 'x';
char w = (char)(x - 1);
System.out.println(w);

That will output w .

Because 1 is an int . You need a cast. Like,

char w = (char) (x - 1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM