-6

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

Anoop M Maddasseri
  • 10,213
  • 3
  • 52
  • 73
Hem
  • 1

5 Answers5

0
  1. split the string by "-"
  2. store the index0 and index1 in 2 different variables.
  3. use - operator to subtract index1 from index0
SpringLearner
  • 13,738
  • 20
  • 78
  • 116
0
    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);
Bhuwan Prasad Upadhyay
  • 2,916
  • 1
  • 29
  • 33
0

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"

Community
  • 1
  • 1
hsnkhrmn
  • 961
  • 7
  • 20
0

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.

Community
  • 1
  • 1
Jose Luis
  • 994
  • 1
  • 8
  • 22
-1

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;
    }
Haseeb Anser
  • 494
  • 1
  • 5
  • 19