简体   繁体   中英

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. I know how I can calculate with the Integers( so the 10), but i´m not sure how I can "convert" the Variable name.

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. 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. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM