私は文字列内のすべての数字を見つけて、それらと簡単な算術をする必要があります。 2つの数字の間の記号の数が偶数の場合、演算子は'+'、奇数の場合演算子は' - 'です。文字列から数値を抽出し、それらの間の要素を数えるにはどうすればよいですか?
入力:10plus5 - 出力:15; (10 + 5);
入力:10i5can3do2it6 - 出力:10; (10-5-3 + 2 + 6);
入力:10i5can3do2it - 出力:4。 (10-5-3 + 2)である。
Iは、第一の例の解を見つけることができる:
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);
}
だけ。また、 'カウント%2 == 0 'の比較が起こることを必要 –
最後の計算を得るようにするには、ループ上result'たびに'の値を上書きループの外側にあります。実際には、ループは必要ありません。 'if(array.length%2 == 0)'は比較対象となります –
Thaks私はこれを修正しますが、私の問題は他の例です。 –