首页 > 解决方案 > 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.

标签: javastringconditional-statementsbluej

解决方案


您不是在“比较双值”,实际上您根本没有比较任何东西。字符串是字符串,而不是真/假值,因此不兼容类型错误。(澄清一下,Java 看到一个字符串:if("Double.valueOf(String[2]) > 20"){}not if(Double.valueOf(String[2]) > 20){}

我可能只是在比较运算符上使用一个开关(确保它是一个字符串而不是一个字符):

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

编辑:我做了一些搜索,发现了这个,我以前没见过,但可能有用。


推荐阅读