How can I evaluate the expression from the string? [duplicate] - java

This question already has answers here:
How to evaluate a math expression given in string form?
(26 answers)
Closed 6 years ago.
I want to evaluate the expression from a string..
public static void main(String[] args) {
String test = "2+3";
System.out.println(Integer.parseInt(test));
}
It returns me a NumberFormatException error..How do I fix this?

That won't work with basic java (AFAIK), maybe with some expression evaluator library.
You have to parse the string. E.g.:
String[] nums = string.split("+");
List<Integer> numbers = new ArrayList<Integer>();
for(String num : nums) {
numbers.add(Integer.parseInt(num));
int result = addNumbers(numbers);
Where addNumbers is a method you wrote to add numbers in a list.
If you have more operations you have to parse the operators as well, building an expression tree then traversing it.

Related

Java double calculate and convert to String [duplicate]

This question already has answers here:
Converting double to string
(17 answers)
Closed 1 year ago.
so I got a Problem coding in Java.
I have some doubles declared and I need to calculate with them. But I dont know who I convert the doubles to a result that can be posted in a JLabel as a String. It always says something like: cannot convert double to String. I have tried toString method but I am either doing it wrong or it just doesnt work. Any ideas for a working code?
You can use String#valueOf.
Demo:
public class Main {
public static void main(String[] args) {
double val = 12.34;
String strVal = String.valueOf(val);
System.out.println(strVal);
}
}
Output:
12.34

Save multiple array in a String [duplicate]

This question already has answers here:
How to convert a char array back to a string?
(14 answers)
Closed 3 years ago.
My problem is I have 4 arrays, a[1]=1, a[2]=3, a[3]=4, a[4]=5, and want to save as new string/ char, so the output will be s[ ]={1345}
I try to define like this, but it doesn't works
char s[]= new char [5];
s={'a[1]','a[2]','a[3]','a[4]'};
Instead of initialising the char array s[] and then setting the value in the next line, you can directly initialize the array like: char s[] = {a[0], a[1], a[2], a[3]};
In Java the concept of String is fairly simple. You dont have to define it as a character array. Just take a String variable and concat the array values to it. The below is how you can do it.
public static void main(String[] args) {
int[] a = {1,2,3,4};
String output = a[0]+a[1]+a[2]+a[3];
System.out.println(output);
}
Hope it shall work for you.

How split over a string with a first and last index using java? [duplicate]

This question already has answers here:
Regular expression to extract text between square brackets
(15 answers)
Closed 4 years ago.
I want to split over a string (exemple : ABC-{9090}) with a first and last index using java
I want to get just the value between {} --> output : 9090
You can use below replaceAll for this purpose:
public class StringParsing {
public static void main(String[] args){
String s = "ABC-{9090}";
System.out.println(s.replaceAll("[^\\{]+\\{(.*?)\\}.*", "$1"));
}
}

Why I can't I convert the string "(2+2)" to an integer (java)? [duplicate]

This question already has answers here:
How to evaluate a math expression given in string form?
(26 answers)
Closed 5 years ago.
I want convert a string to an integer but it doesn't work. I think the problem is that the string isn't "clean", see this example:
public class Test{
public static void main(String[] args){
String str = "(2+2)";
int conv = Integer.parseInt(str);
System.out.println(conv);
}
}
Why doesn't it work? I could also define int x = (2+2); without any problems.
What exactly is the problem here and is there an easy way to solve it?
*Purpose: I have just finished a code that will detect if a math expression is correct (brackets, signs, .. arithmetic stuff). As example the string input is ((8+7)*2) and the program will return true.
But now I need to find a way to calculate this and return the solution of it, 30. (If you want I can post my code too but I didn't want make this question seemingly long.)
Integer.parseInt expects a string, however it needs a number in a string format.
The (2+2) is a string, and it cannot compute 2+2. So trying to convert non numeric values won't work. (), and + are non numeric values
UPDATE:
From my research you can use built-in Javascript engine.
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
public class Main {
public static void main(String[] args) throws ScriptException {
String str = "2+2";
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
System.out.println(engine.eval(str));
}
}
Why doesn't it work?
The String cannot be parsed to an integer due to some of the invalid characters within here:
"(2+2)"
You simply cannot parse invalid characters such as ( ) and + using Integer.parseInt. However, when + is the only character used and is a leading sign it's valid i.e
String strOne = "+2";
String strTwo = "+2345";
String strThree = "+237645";
etc...
is there an easy way to solve it?
There is no built-in method to do this for you. However, you can have a look at other posts relating to your question:
Evaluating a math expression given in string form
How to parse a mathematical expression given as a string and return a number?

How to make int expressions calculated in returned value from Integer.parseInt(str) [duplicate]

This question already has answers here:
How to evaluate a math expression given in string form?
(26 answers)
Closed 6 years ago.
Java code...
If I have
int num = 10 + 5;
System.out.println(num);
The result is 15
And if I have
String str = "10";
int number = Integer.parseInt(str);
System.out.println(number);
The result is 10
But if I have
String str = "10 + 5"; //here the problem.
int number = Integer.parseInt(str);
System.out.println(number);
The result is error message.
How to do it correctly. What I want to implement is to take expression from a String and calculate it. I am forced to take it from a String because I take it from JTextfield, so I want to make the calculation for the returned String expression.
There is no simple way to do it directly because you need some sort of "expression evaluator". One way would be to use a javascript engine from the scripting library:
public static void main(String[] args) throws Exception {
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("JavaScript");
String s = "10 + 5";
int result = ((Double) engine.eval(s)).intValue();
System.out.println(result); // 15
}
Looks like a similar question was already answered: Is there an eval() function in Java?
You could however write a pretty simple parser by splitting the string into an array and writing an algorithm to handle the operations.
You will have to write an expression parser to separate out operands and operators and then accordingly perform the operations. You cannot pass 10 + 5 to Integer.parseInt() and expect the evaluated result.

Categories

Resources