简体   繁体   English

在Java中为char分配负值

[英]Assign negative value to char in Java

I want to assign a negative value to char in Java. 我想为Java中的char分配一个负值。 Example: char a='-1' I tried the below example but an error occurs. Example: char a='-1'我尝试了以下示例,但发生错误。

 char[] temp=new char[10];
    for(int i=0;i<10;i++)
    {
        if(condition met)
        temp[i]='-1';
    }

'-' and '1' are two separate char s, and they cannot be stored in a single char variable. '-''1'是两个单独的char ,它们不能存储在单个char变量中。 Use a String instead. 使用String代替。 If you are using -1 as some sort of an exit case, use some alphabetical character instead like x . 如果您使用-1作为某种退出情况,请改用一些字母字符,例如x

You can do this, but char is 16-bit unsigned int so it will result in the char actually being 65535. See this answer for more info. 您可以执行此操作,但是char是16位unsigned int,因此它将导致char实际上为65535。有关更多信息,请参见此答案

char a = (char)-1;
char b = (char)0;
System.out.println((int)a);
System.out.println((int)b);

Will result in output of: 将导致输出:

65535                                                                                                                                                                                        
0                                                                                                                                                                                            

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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