gpt4 book ai didi

java - 带字符串比较的动态 if 语句求值问题

转载 作者:太空宇宙 更新时间:2023-11-04 08:53:29 25 4
gpt4 key购买 nike

我尝试了 this thread 中给出的示例使用 BeanShell 动态创建 if 语句。但它工作得不好。我在下面的示例中使用了字符串,而不是使用“age”变量作为整数。我得到的答案是“失败”而不是“成功”。

有人可以帮助我吗?

/*
To change this template, choose Tools | Templates
and open the template in the editor.
*/

import java.lang.reflect.*;
import bsh.Interpreter;

public class Main {
public static String d;

public static void main(String args[])
{
try {
String age = "30";

String cond = "age==30";


Interpreter i = new Interpreter();

i.set("age", age);

System.out.println(" sss" + i.get("age"));

if((Boolean)i.eval(cond)) {
System.out.println("success");
} else {
System.out.println("fail");
}
}
catch (Throwable e) {
System.err.println(e);
}
}
}

谢谢,玛尼

最佳答案

您必须选择数字比较或字符串比较。这需要使用与年龄兼容的条件和类型。

数字:

  int age = 30;
String cond = "age==30";

字符串:

  String age = "30";
String cond = "age.equals(\"30\")";

关于java - 带字符串比较的动态 if 语句求值问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2838801/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com