【发布时间】:2016-06-05 19:21:07
【问题描述】:
我正在尝试编写一个采用 String 的方法,在其中查找 Ints 然后将它们相加。
例如:
String s = "five5six66"
应该返回 5+66 = 71 或者:
String s = "1ciao2three3"
应该返回 1+2+3 = 6
以下是我已经写的,但是当我运行它时,我得到了一个
NumberFormatException
代码(更新 1):
public static int addNumbers(String s) {
String numbers="";
int addNumbers = 0;
int i;
char c;
for (i=0; i<s.length(); i++) {
if (s.charAt(i)>='0' && s.charAt(i)<='9') {
c = s.charAt(i);
while (i<s.length()-1) {
if (s.charAt(i+1)>='0' && s.charAt(i+1)<='9')
numbers = numbers.valueOf(c + s.charAt(i+1));
addNumbers = addNumbers + Integer.parseInt(numbers);
}
addNumbers = addNumbers + Character.getNumericValue(c);
}
}
return addNumbers;
}
希望你能帮我修复这段代码,请让我明白我做错了什么!
如果我有这样的字符串,我也可以扩展它:
String s = "hi123and27"
我可以得到 123+27 = 150?
因为我现在的代码仅限于 2 位数字。
【问题讨论】:
-
考虑对该方法使用正则表达式
-
This:
s.charAt(i+1)在 for 循环中是一件非常危险的事情。想一想为什么,问题就会变得显而易见。 -
@HovercraftFullOfEels 谢谢我明白了!这就是为什么我得到 IndexOutOfBound 但是我怎样才能在一个字符串中连接 2 个连续的数字呢?
-
您可以将 char 存储在一个变量中,如果下一个 char 仍然是数字,则将它们连接起来——即向后看但不要向前看。您遇到了“边界条件”,需要仔细考虑。
-
好的!我会尝试更新我的代码!