Reputation: 1
i have the three variable int value1,value2 and a String operator. and i want to check the if Condition. suppose value1=4,value2=3 and in operator='>'. then how i check the if condition for Example -
int value1=4;
int value2=3;
String operator=">";
if (value1+operator+value2)
{
System.out.println("hello");
}
i know the this is wrong but how to correct it..
Upvotes: 0
Views: 94
Reputation: 4902
Compare two integers in java like this:
if (value1 > value2) {
System.out.println("Hello");
}
You shouldn't be putting the operator into a string. In java, '+' is used for addition of numbers, and concatenation of strings, not to build expressions.
Upvotes: 0
Reputation: 6622
value1+operator+value2 will be a string only not boolean which is needed in if
so instead of if (value1+operator+value2)
put if (value1 > value2)
Upvotes: 0
Reputation: 2933
Probably the simplest way would be to make an if
statement for each available operator that you expect to use.
int value1=4;
int value2=3;
String operator=">";
if(operator.equals(">"))
{
if(value1 > value2)
{
System.out.println("hello");
}
}
else if(operator.equals("<"))
{
// And so on...
}
Upvotes: 1
Reputation: 106508
You won't be able to use the String directly. You have to check to see what kind of operator it is to begin with, then perform the explicit math operation.
public boolean applyOperator(String op, int a, int b) {
if (">".equals(op)) {
return a > b;
} // the others are an exercise to the reader.
}
// later in the code
if(applyOperator(operator, value1, value2)) {
System.out.println("Hello world!");
}
Upvotes: 1
Reputation: 45080
You can simply give this.
if (value1 > value2)
Btw, why do you want to give the operator
in a String
and then, use that String
instead of an operator as such? Is there any special requirement for that? In that case, @Makoto's answer is a good bet for you.
Upvotes: 0