java - 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;
- 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])
- Then asks the user to choose how he wants to filter: >,<,>=,<=, from int x to int y.
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.
解决方案
您不是在“比较双值”,实际上您根本没有比较任何东西。字符串是字符串,而不是真/假值,因此不兼容类型错误。(澄清一下,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 ...
}
编辑:我做了一些搜索,发现了这个,我以前没见过,但可能有用。
推荐阅读
- mocking - 如何有效地为每个微服务的独立测试创建 API 模拟?
- javascript - 如何发送http请求以仅在响应发生更改时获取响应
- linux - 以线性方式循环遍历子文件夹和文件
- c++ - 如何检测 Qt 应用程序(WIN & MAC)是否挂起
- c# - 通过引用将字节从 C# 传递到 C++/CLI 包装器以调用 InterlockedOr8 函数
- sql - 左连接和 where 表达式中不使用 CTE 检索行
- java - 在这个移动的 x 矩阵中我的构造函数有什么问题?
- javascript - 打字稿 - 不能分配给从不打字
- mysql - 如果我修改主键的类型,auto_increment 会保持不变吗?
- opengl - OpenGL 着色器输入参数中的非显式布局绑定问题——为什么?