[英]How to perform ASCII subtraction in java
I've got a char[]
array named temp
which only contains a
, b
or c
. 我有一个名为
temp
的char[]
数组,其中仅包含a
, b
或c
。 Now if the two adjacent characters in the array are distinct, ie temp[j]
and temp[j+1]
contains a
and b
respectively, I need to store c
in temp[j+1]
. 现在,如果数组中的两个相邻字符是不同的,即
temp[j]
和temp[j+1]
分别包含a
和b
,则需要将c
存储在temp[j+1]
。
And for that, I defined, 为此,我定义了
private static final int CHARSUM = 294;
which is the sum of ASCII value of a
, b
and c
. 这是
a
, b
和c
的ASCII值之和。 and what I tried was to subtract the sum of temp[j]
and temp[j+1]
from 294
. 我试图从
294
减去temp[j]
和temp[j+1]
和。
temp[j+1] = CHARSUM-(temp[j]+temp[j+1]);
which should store the value c
if the other values were a
and b
. 如果其他值为
a
和b
,则应存储值c
。 But here, the problem is: 但是在这里, 问题是:
incompatible types: possible lossy conversion from int to char
不兼容的类型:从int到char的可能的有损转换
And I tried changing to: 我尝试更改为:
private static final char CHARSUM = "294";
temp[j+1] = (char)CHARSUM-(temp[j]+temp[j+1]);
temp[j+1] = Character.getNumericValue(CHARSUM-(temp[j]+temp[j+1]));
However, none of those did work and I did not find any other answers that would help me to solve the problem. 但是,这些都没有起作用,我没有找到任何其他答案可以帮助我解决问题。 So Any help to fix this will be highly appreciated.
因此,任何解决此问题的帮助将不胜感激。 Thanks.
谢谢。
您可以将减法的结果转换为char:
temp[j+1] = (char)(CHARSUM-(temp[j]+temp[j+1]));
In Java, a char
is "really" a whole number between 0
and 65535
. 在Java中,
char
是“真正的”整数,介于0
和65535
之间。 If you want to assign an int
outside that range to a char
variable, an explicit cast is required. 如果要将超出范围的
int
分配给char
变量,则需要显式强制转换。
For example 例如
char c = 65535; // ok
char c = 65536; // doesn't compile
char c = (char) 65536; // compiles, but it's a lossy conversion
Even though for your values, CHARSUM-(temp[j]+temp[j+1])
is always in that range, the compiler can't tell that because it is not a compile time constant. 即使你的价值观,
CHARSUM-(temp[j]+temp[j+1])
总是在这个范围内,编译器不能告诉大家,因为它不是一个编译时间常数。 Therefore you need to apply a cast to the entire expression: 因此,您需要对整个表达式进行强制转换:
temp[j+1] = (char) (CHARSUM-(temp[j]+temp[j+1]));
Your approaches did not work, for reasons I'll explain: 您的方法无效,原因如下:
"294"
is a String
, not an int
. "294"
是一个String
,而不是一个int
。 CHARSUM
- the entire expression is still an int
. CHARSUM
仅应用于CHARSUM
整个表达式仍然是int
。 getNumericValue
returns an int
not a char
, so you'd have to cast. getNumericValue
返回一个int
而不是char
,因此您必须进行强制转换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.