如何创建5个项目的数组,然后为每个项目创建一个数组?我知道如何创建一个包含5个项目的数组,但我遇到的问题是为每个项目创建一个数组。我假设我需要5个数组,因为有5个项目。
int gas = 0;
int food = 0;
int clothes = 0;
int entertainment = 0;
int electricity = 0;
int[] budget = new int[4];
budget[0] = gas;
budget[1] = food;
budget[2] = clothes;
budget[3] = entertainment;
budget[4] = electricity;
提前致谢
答案 0 :(得分:1)
不是创建一个二维数组,其中包含逻辑上组合在一起的金额类型(我假设每月),最好定义一个数据持有者类,以便您可以使用他们的名称而不是易出错的指数。
例如(减去getter和setter):
public class Budget {
public int gas = 0;
public int food = 0;
public int clothes = 0;
public int entertainment = 0;
public int electricity = 0;
};
// ....
Budget[] months = new Budget[12];
budget[0].gas = gasCosts;
budget[0].food = foodCosts;
// etc
答案 1 :(得分:0)
您是说要创建2D阵列?预算数组中的每个元素都是另一个数组?
你使用循环。
int[] budget = new int[5]; //There are 5 elements to be stored in budget, not 4
for (int y = 0; y < 5; y++) {
budget[y] = new int[5];
}
答案 2 :(得分:0)
也许你需要一个矩阵。
int[][] budget = new int[4][4];
在第一个索引中保留预算,在第二个索引中保留五个(在上面的情况下)预算项目。 当你有一个矩阵[x] [y]时,你有x + 1个数组,每个数组都有y + 1个元素。
答案 3 :(得分:0)
数组中有5个元素。
int[] budget = new int[5];
budget[0] = gas;
budget[1] = food;
budget[2] = clothes;
budget[3] = entertainment;
budget[4] = electricity;
你需要二维数组,它基本上是一个数组数组。 2D数组由2对[]声明。在以下示例中,每个budget
都有10个详细信息。
String[][] detail = new String[budget.length][10];
答案 4 :(得分:0)
如果我正确理解你,你需要一个类似于......的二维数组
int gas = 0;
int food = 1;
int clothes = 2;
int entertainment = 3;
int electricity = 4;
int maxEntries = 10;
int[][] myArray = new int[5][maxEntries];
可以通过以下方式访问:
myArray[gas][entryNumber] = 6;
int value = myArray[gas][entryNumber];
但这是多么不灵活?您必须事先知道每个“类别”将有多少条目,或者在添加项目时使用代码检查给定的数组长度,在需要更大的数据时创建新数组(并复制旧数据)进入它。)
你可能想要的至少是ArrayList
ArrayList
s:
ArrayList<ArrayList<Integer>> my2dArrayList =
new ArrayList<ArrayList<Integer>>();
...
my2dArrayList.get(gas).add(someValue);
int myValue = my2dArrayList.get(gas).get(index);
或HashMap
ArrayList
您可以通过类别名称访问HashMap<String, ArrayList<Integer>> myMap =
new HashMap<String, ArrayList<Integer>>();
...
myMap.get("gas").add(someValue);
int myValue = myMap.get("gas").get(index);
:
{{1}}