gpt4 book ai didi

java - java中对字符的操作

转载 作者:太空宇宙 更新时间:2023-11-04 06:26:24 25 4
gpt4 key购买 nike

我有这个方法:

public static String appliquerCoup( String combinaison, String coup ){
String res = "";
for(int i = 0; i < 3; i++){
res = res + (combinaison.charAt(i) - coup.charAt(i));
}
return res;
}

如果我在 main 中应用这个

System.out.println(appliquerCoup("414", "020")

我有:

4-14

尽管符合逻辑,但它为我提供了 -1 来表示 2-1 = -1如果操作低于 0,我希望它把我置为 0。

所以我做了这些改变:

public static String appliquerCoup( String combinaison, String coup ){
String res = "";
for(int i = 0; i < 3; i++){
char cFinal = combinaison.charAt(i) - coup.charAt(i);
if(cFinal < '0')
cFinal = 0;
res = res + cFinal;
}
return res;
}

但它告诉我在第四行有

possible loss of precision
found :int; required: char

你能帮我找到解决方案吗?我已经尝试了很长时间了。

非常感谢

最佳答案

一个字符减去另一个字符的结果是一个整数。它告诉您它们之间的距离。

假设您正在计算'b' - 'a'。它们之间的区别在于数字1,而不是字符'1'

您可以将 cFinal 更改为 int 并且它应该可以工作,因为将整数附加到字符串是合法的:

int cFinal = combinaison.charAt(i) - coup.charAt(i);
if (cFinal < 0) // NB: compare with 0, not '0'
cFinal = 0;
res = res + cFinal;

或者您可以使用max更简洁地执行下限。

res += Math.max(0, combinaison.charAt(i) - coup.charAt(i));

关于java - java中对字符的操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26747281/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com