我今年正在参加在线AP计算机科学课程,我们刚刚开始使用字符串和相关方法。本周我任务的一部分是完成一些CodingBat String 3练习问题,我陷入了Sumnumumbers。该代码应该取一个字符串,并在其中添加所有数字(不是数字)。例如," 13TET6"应输出19。我评论了我的代码,以显示我认为该代码应该运行的方式。
public int sumNumbers(String str) {
int place, length, sum;
length = str.length(); //Gets length of string
place=0;
sum=0;
String number = "";
while(place<length){ //This loop will stop when we reach the last character of the string
while(Character.isDigit(place)){ //This checks if the char at place is a digit
number+=str.charAt(place); //If so it adds it to the String number
place++; //This moves along the string to check the next character
}
if(!(number=="")) //This will only add the number to the sum if it has a number stored
sum+=Integer.parseInt(number); //This will add the number to the sum by
//Converting the string to an integer
number=""; //This resets the number string so it can read the next number
place++; //This moves the loop along
}
return sum;
}
这应该输出字符串中的数字总和,但始终输出0。我替换了底部的if语句,每次存储在其中的数字"中的数字都会添加1个。它始终输出字符串的长度,因此我知道whir(targe.isdigit(place))循环永远不会正确运行。我不知道为什么,我可能只是缺少简单的东西。
您的第二个循环是错误的。您检查字符。ISDIGIT(位置),但这始终是正确的,因为您正在检查一个号码!位置是您要检查的字符串中的位置。这应该是:
Character.isDigit(str.charAt(place))
这引入了第二个问题。由于您的最后一个字符是一个数字,因此while循环将检查下一个值,但由于它超出了界限。因此,添加一张检查,您的时光将如下所示:
while (!(str.length() <= place) && Character.isDigit(str.charAt(place)))