[英]How do I use string variable names in Math equations?
try {
BufferedReader rd = new BufferedReader(new FileReader("tommy.txt"));
String text;
while ((text = rd.readLine()) != null) {
println(text);
int i = Integer.parseInt(text);
GRect block = new GRect(i, i, i, i);
add(block);
}
} catch (IOException e) {
e.printStackTrace();
}
So I have a .txt that I import with Strings like" SIZE/10" with SIZE being a constant that is defined in the code. 因此,我有一个.txt文件,其中导入了“ SIZE / 10”之类的字符串,其中SIZE是代码中定义的常量。 I know how I can calculate with the Integers( so the 10), but i´m not sure how I can "convert" the Variable name. 我知道如何使用Integers(即10)进行计算,但是我不确定如何“转换”变量名称。
Thanks for the help. 谢谢您的帮助。
Similar to https://stackoverflow.com/users/1682559/kevin-cruijssen comment - if these truly are constants as you write, and you know what will they be at the time of writing the code it's not that difficult of a problem. 类似于https://stackoverflow.com/users/1682559/kevin-cruijssen注释-如果这些在编写时确实是常量,并且您知道编写代码时它们将是什么,那么问题就不那么困难了。 I suggest using an enum like so: 我建议使用这样的枚举:
public enum ConstantsEnum{
SIZE(20)/*...*/;
private int value;
ConstantsEnum(int value){
this.value = value;
}
public int getByName(String name){
return ConstantsEnum.valueOf(name).getValue();
}
public int getValue(){
return value;
}
}
with that, whenever you read a string constant call ConstantsEnum.getByName(name)
and voila, you have your value. 这样,每当您读取一个字符串常量调用ConstantsEnum.getByName(name)
和voila时,您便会拥有自己的值。 You could drop the enum idea and create a simple Map<String,Integer>
(or <String,Whatever_your_values_will_be>
) to store and get values for dynamic names. 您可以放弃枚举方法,并创建一个简单的Map<String,Integer>
(或<String,Whatever_your_values_will_be>
)来存储和获取动态名称的值。
The hard part might be reading the file to correctly get and convert each name into it's value - but that will depend on file structure and variable names which you did not mention. 困难的部分可能是读取文件以正确获取每个名称并将其转换为它的值-但这将取决于您未提及的文件结构和变量名称。 Possibly a simple series of replaceAlls on file content converting all variable names to values will be sufficient. 可能需要执行一系列简单的关于文件内容的replaceAlls,将所有变量名转换为值就足够了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.