我想取字符串:“6 + 3”; “6 - 3”,“6/3”和“6 * 3”并且能够进行所需的算术运算。我知道我必须使用正则表达式来执行此操作。到目前为止,我有:
int num1 = 0, num2 = 0, count = 0;
Scanner input = new Scanner(System.in);
Pattern stringPattern = Pattern.compile("\\d+|[+-/*]");
System.out.println("Please enter an arithmetic operation: ");
String arith = input.nextLine();
Matcher stringMatch = stringPattern.matcher(arith);
while(stringMatch.find()){
System.out.println(stringMatch.group());
if(Integer.parseInt(stringMatch.group()) >=Integer.MIN_VALUE){
if(count == 0){
num1 = Integer.parseInt(stringMatch.group());
}
else{
num2 = Integer.parseInt(stringMatch.group());
}
count++;
}
}
我遇到的问题是从字符串中获取算术符号并将其用作一元运算符。