I want to take the string(s): “6 + 3”; “6 – 3”, “6 / 3” and “6 * 3” and be able to do the required arithmetic operation. I know that I have to use a regular expression to do this. So far, I have:
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++;
}
}
The problem I have is getting the arithmetic sign out of the string and using it as an unary operator.