Use a String as a conditional in java (Convert String to boolean)

I am new here!

I am doing a school project where I take a .csv file as input and read every line of values and store them into a String[], and then create an ArrayList.

The CSV file has some temperature measurements and I'm required to make filters for the different temperature measurements. What I want to know if there is a way to make the condition of an if statement the value of a string.

Since there are different ways to filter the information (>,<,>=,<=, from int x to int y) I want to create a method that concatenates a string that creates the condition the user is looking for;

  1. Prompts user to choose what data from the array he wants to filter by.

    (For instance option 3, which means its the data stored in String[2])

  2. Then asks the user to choose how he wants to filter: >,<,>=,<=, from int x to int y.
  3. Finally asks the remaining value to finish the comparison.

    From these prompts we could build:

    String a = String[2] + (comparison operator) + comparison value.

    For example a = String[2] + " > 20"

Then I want to use the 'a' like this: if(a){}

Where the console should read this as: - - - - - - - if(Double.valueOf(String[2]) > 20){}

My IDE is BlueJ which tells me incompatible types: java.lang.String cannot be converted to boolean. You may wonder why I use a String[] if I'm comparing double values,

Thanks in advance and my apologies if my idea is preposterous or not clear.

Upvotes: 0

Views: 2285

Answers (2)

user3060729
user3060729

Reputation: 86

If you want to evaluate conditions from Strings you could use something like this:

public static void main(String[] args) {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("JavaScript");
        try {
            Boolean eval = (Boolean) engine.eval("40 > 10");
            assert(eval);
        } catch (ScriptException e) {
            e.printStackTrace();
        }
    }

Upvotes: 0

17slim
17slim

Reputation: 1233

You're not "comparing double values", and in fact you aren't comparing anything at all. A string is a string, not a true/false value, hence the incompatible types error. (To clarify, Java sees a string: if("Double.valueOf(String[2]) > 20"){} not if(Double.valueOf(String[2]) > 20){})

I would probably just use a switch on the comparison operator (make sure it's a string not a char):

switch(operator) {
    case ">":
        doStuffGreaterThan();
        break;  // Needed or else it will continue into the next cases too
    case "<":
        doStuffLessThan();
        break;
    case ">=":
        doStuffGE();
        break;
    ... etc ...
}

Edit: I did a bit of searching and found this, which I haven't seen before but may be useful.

Upvotes: 1

Related Questions