I want to make a Java program in which I want to take a String as a input. The string will have two integer numbers and operation to be performed. eg. 25+85 or 15*78
The output will the solution of the string.
But I don't know how to split the string because operator sign is not known before execution.
You would want to check what operation it is using by using String.contains("+");
and checking all the other operators you want to support. Then split wherever that operator is, String.split("+")
. From there parse the output of String.split("+")
by using Integer.parseInt(String s)
and then return the sum. Pretty simple, good luck.
You can use the split()
method of the String class to split the input at non-digit characters:
input.split("\\D");
This will give you an array containing only the numbers. I guess you also want to get the operator somehow? Although it's not the most elegant way, you might want to start with input.replaceAll("[^\\\\*\\\\+\\\\-\\\\/]", "")
to remove everything that's not an operator, but you will still have to do some careful input filtering. What if i type 5+4*6
oder 2+hello
?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.