【发布时间】:2020-03-09 18:53:23
【问题描述】:
我想从用户那里获取字符串类型的输入 并找到前 2 个数字并将它们相乘并将结果替换为文本 用户应该把命令字放在前面,命令是:mul 例如: mul hello 2 car ?7color 9goodbye5 结果应该是:14color 9goodbye5 我写了这段代码,但它不工作 你能帮我解决这个问题吗?
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Collusion {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
String patternString = "((\\d+).+(\\d+))";
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(input);
String text = matcher.group(0);
String found = matcher.group(1);
String thirdGroup = matcher.group(2);
String fourthGroup = matcher.group(3);
int firstNum = Integer.parseInt(thirdGroup);
int secondNum = Integer.parseInt(fourthGroup);
int integerMultiple = firstNum * secondNum ;
String multiple = String.valueOf(integerMultiple);
while (matcher.find()) {
String result = text.replace(multiple , found);
System.out.println(result );
}
}
}
【问题讨论】:
-
我写了这段代码,但它不起作用你能说得更具体一点吗?
-
“它不起作用”不是有效的问题陈述。阅读ericlippert.com/2014/03/05/how-to-debug-small-programs
标签: java regex string stringbuilder