Java 我的代码有什么错误?
我正在尝试编写一个程序,使用递归确定字符串中的数字之和,我认为下面的代码会将“总和为6”打印到控制台,但它会输出“代码为150” 有人能告诉我我的错误是什么吗Java 我的代码有什么错误?,java,string,recursion,sum,Java,String,Recursion,Sum,我正在尝试编写一个程序,使用递归确定字符串中的数字之和,我认为下面的代码会将“总和为6”打印到控制台,但它会输出“代码为150” 有人能告诉我我的错误是什么吗 public class SumOfString { public static String Test = new String(); public static Integer count = new Integer(0); public static Integer sum = new Integer(0); public sta
public class SumOfString {
public static String Test = new String();
public static Integer count = new Integer(0);
public static Integer sum = new Integer(0);
public static long sumThis(String s){
if (count< s.length()){
if (Character.isDigit(s.charAt(count))){
int digit = s.charAt(count);
count++;
sum += digit;
return sumThis(s);}
else{
count++;
return sumThis(s);}}
else{
return sum;}}
public static void main(String[] args) {
Test= "1a2b3c";
System.out.println("The sum is " + sumThis(Test));
}
公共类SumOfString{
公共静态字符串测试=新字符串();
公共静态整数计数=新整数(0);
公共静态整数和=新整数(0);
公共静态长sumThis(字符串s){
如果(计数
在不为您解决问题的情况下:
代码中的一个bug是:
int digit = s.charAt(count);
在计数为0的字符串“1”上测试此代码段。它不会返回整数1。若要获得该值,需要包装此调用:
Character.getNumericValue(s.charAt(count));
您应该养成在调试器中运行代码的习惯。导致这种情况的原因是
int digit=s.charAt(计数);
charAt
将返回一个字符原语,因此它将是该字符的十进制值
Character = Decimal Value
`1` = 49
`2` = 50
`3` = 51
-------
150
您需要将字符转换为int:查看ascii表,因为您将看到
“1”
的值为49,“2”
的值为50,“3”
的值为51和150
试一试
一个错误,应该是这样的谢谢,我不认为这会引起问题。谢谢,我以后会尽量记住的。
int digit = s.charAt(count) - 48;