gpt4 book ai didi

java - 将字符串转换为整数成员,可能吗?

转载 作者:行者123 更新时间:2023-11-29 07:14:54 25 4
gpt4 key购买 nike

好吧,我的问题并不严重,我只是想找到一种访问/修改类成员变量的巧妙方法。这是代码:

public class Storage{
private int cookies= 0;
private int rolls= 0;
private int candies= 0;
private int lolipops= 0;
private int iceCreams= 0;

public void addCookies(int howMuch){ //this is the dirty way of creating method for
this.cookies = cookies+howMuch; //every member variable
}

public void addValue(String stat, int howMuch){ //i would like to do it only
//by passing the name
//of variable and then cast it as integer
//so that it would relate to my class members

int value = this.(Integer.parseInt(stat)); // <- YES i know its ridiculous
//im just trying to explain what is my aim
value = value + howMuch;

this.(Integer.parseInt(stat)) = value;
}
}

通常我想通过将名称传递给方法来访问字段,读取该成员的值,向其添加一些值,然后存储它。是的,我知道它可以很容易地用单独的方法来完成,甚至可以通过使用一些数组列表和成员名称与传递给方法的参数的比较来完成。但我想在不编写冗余代码的情况下“快速”完成。

现在我有大约 5 个成员,但是 15000 个呢?我的目标是简化整个处理和代码编写。那么一般这样的冗余代码写绕过有没有可能呢?因为我知道我将始终将适当的名称传递给方法...除非经验法则是为每个变量创建方法?

最佳答案

通常您会使用像 map 这样的集合。

public class Storage{
private final Map<String, Integer> inventory = ...

public void addCount(String key, int count) {
Integer i = inventory.get(key);
if (i == null) i = 0;
inventory.put(key, i + count);
}

关于java - 将字符串转换为整数成员,可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10468807/

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