![](/img/trans.png)
[英]How do I use the ActionEvent function with my code to do math equations
[英]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();
}
因此,我有一個.txt文件,其中導入了“ SIZE / 10”之類的字符串,其中SIZE是代碼中定義的常量。 我知道如何使用Integers(即10)進行計算,但是我不確定如何“轉換”變量名稱。
謝謝您的幫助。
類似於https://stackoverflow.com/users/1682559/kevin-cruijssen注釋-如果這些在編寫時確實是常量,並且您知道編寫代碼時它們將是什么,那么問題就不那么困難了。 我建議使用這樣的枚舉:
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;
}
}
這樣,每當您讀取一個字符串常量調用ConstantsEnum.getByName(name)
和voila時,您便會擁有自己的值。 您可以放棄枚舉方法,並創建一個簡單的Map<String,Integer>
(或<String,Whatever_your_values_will_be>
)來存儲和獲取動態名稱的值。
困難的部分可能是讀取文件以正確獲取每個名稱並將其轉換為它的值-但這將取決於您未提及的文件結構和變量名稱。 可能需要執行一系列簡單的關於文件內容的replaceAlls,將所有變量名轉換為值就足夠了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.