How to convert string to int to get calculation
String a="2-1";
How to convert this string to int to get value as 1
How to convert string to int to get calculation
String a="2-1";
How to convert this string to int to get value as 1
String a = "2-1";
String[] split = a.split("-"); //split string by regex -
int rs = Integer.valueOf(split[0]) - Integer.valueOf(split[1]); //parse string to integer and subtract
System.out.println("Result= " + rs);
If your strings are in x-y simplicity, it's best to split and do operations as suggested in other replies.
However if you want more complext evaluations e.g (x+y)/2*z-2, you need an expression evaluator. See this post: "Evaluating a math expression given in string form"
You could find another anwers in here: Is there an eval() function in Java?
In javascript, eval() does what you want. In that link you could see the alternatives to eval(), in Java.
Here is the complete function for subtraction and addition you can edit it for other operators too:
public int getResult() {
String input = "2-1";
char[] charArray = input.toCharArray(); //split string in to three characters
int result = 0;
if(charArray[1] == '-')
{
result = Integer.valueOf(charArray[0]) - Integer.valueOf(charArray[2]); //if input is subtract minus the variables
}
else if (charArray[1] == '+')
{
result = Integer.valueOf(charArray[0]) - Integer.valueOf(charArray[2]); //if input is addition, add the variables
}
return result;
}