在 java 中使用字符串作为条件(将字符串转换为布尔值)

我刚来这地方!

我正在做一个学校项目,我将一个 .csv 文件作为输入并读取每一行值并将它们存储到一个 String[] 中,然后创建一个 ArrayList。

CSV 文件有一些温度测量值,我需要为不同的温度测量值制作过滤器。我想知道是否有办法使 if 语句的条件成为字符串的值。

由于有不同的方法来过滤信息(>、<、>=、<=,从 int x 到 int y)我想创建一个方法来连接一个字符串,该字符串创建用户正在寻找的条件;

  1. 提示用户从数组中选择他想要过滤的数据。

    (例如选项 3,这意味着它的数据存储在 String[2] 中)

  2. 然后要求用户选择他想要的过滤方式:>,<,>=,<=, 从 int x 到 int y。

  3. 最后求剩余值完成比较。

    根据这些提示,我们可以构建:

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

    例如a = String[2] + " > 20"

然后我想像这样使用'a': if(a){}

控制台应将其读作: - - - - - - - if(Double.valueOf(String[2]) > 20){}

我的 IDE 是 BlueJ,它告诉我不兼容的类型:java.lang.String 无法转换为布尔值。你可能想知道为什么我在比较双精度值时使用 String[],

提前致谢,如果我的想法荒谬或不清楚,我深表歉意。


慕村9548890
浏览 84回答 2
2回答

叮当猫咪

您不是在“比较双重值”,实际上您根本没有在比较任何东西。字符串是字符串,而不是真/假值,因此不兼容类型错误。(澄清一下,Java 看到的是一个字符串:if("Double.valueOf(String[2]) > 20"){}not if(Double.valueOf(String[2]) > 20){})我可能只是在比较运算符上使用一个开关(确保它是一个字符串而不是一个字符):switch(operator) {&nbsp; &nbsp; case ">":&nbsp; &nbsp; &nbsp; &nbsp; doStuffGreaterThan();&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; // Needed or else it will continue into the next cases too&nbsp; &nbsp; case "<":&nbsp; &nbsp; &nbsp; &nbsp; doStuffLessThan();&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; case ">=":&nbsp; &nbsp; &nbsp; &nbsp; doStuffGE();&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; ... etc ...}编辑:我做了一些搜索并找到了这个,我以前没见过但可能有用。

慕婉清6462132

如果你想从字符串中评估条件,你可以使用这样的东西:public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; ScriptEngineManager manager = new ScriptEngineManager();&nbsp; &nbsp; &nbsp; &nbsp; ScriptEngine engine = manager.getEngineByName("JavaScript");&nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Boolean eval = (Boolean) engine.eval("40 > 10");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; assert(eval);&nbsp; &nbsp; &nbsp; &nbsp; } catch (ScriptException e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java