【发布时间】:2017-07-27 16:36:14
【问题描述】:
我需要找到字符串中的所有数字并用它们做简单的算术运算。如果两个数之间的符号计数为偶数,则运算符为'+',如果计数为奇数,则运算符为'-'。
输入:10plus5 - 输出:15; (10 + 5);
输入:10i5can3do2it6 - 输出:10; (10 - 5 - 3 + 2 + 6);
输入:10i5can3do2it - 输出:4; (10 - 5 - 3 + 2);
我只能为第一个示例找到解决方案:
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine();
int result = 0;
int count = 0;
Pattern pat = Pattern.compile("([\\d]+)([\\D]+)([0-9]+)");
Matcher match = pat.matcher(input);
while(match.find()){
char[] array = match.group(2).toCharArray();
for (int i = 0; i < array.length; i++) {
int firstNumber = Integer.parseInt(match.group(1));
int secondNumber = Integer.parseInt(match.group(3));
count++;
if(count % 2 == 0){
result = firstNumber + secondNumber ;
}else{
result = firstNumber - secondNumber;
}
}
}
System.out.println(result);
}
【问题讨论】:
-
你每次循环都会覆盖
result的值,所以你只能得到最后一次计算 -
另外,
count % 2 == 0比较需要在循环之外进行。事实上,您不需要循环。if (array.length % 2 == 0)应该是比较 -
谢谢我会解决这个问题,但我的问题是另一个例子。
-
第一个示例有效的唯一原因是因为您只计算最后两个数字,而该示例仅包含两个
标签: java