Java数组问题
我将如何创建一个包含 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;
提前致谢
How would I go about creating an array of say 5 items and then after create an array for each item?. I know how to create an array of 5 items but the problem I have is creating an array for each one after. Im assuming I would need 5 arrays since there's 5 items.
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;
thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
与其创建一个二维数组来保存逻辑上分组在一起的金额类型(我假设每月),不如定义一个数据持有者类,以便您可以使用其名称而不是容易出错的名称来访问金额指数。
例如(减去 getter 和 setter):
Instead of creating a 2-dimensional array holding types of amounts that are logically grouped together (I assume per month) it would be better to define a data-holder class so that you can access the amounts using their name instead of an error-prone index.
For example (minus the getters and setters):
你是说你想创建一个二维数组吗?预算数组中的每个元素都是另一个数组?
你会使用一个循环。
Are you saying you want to create a 2D array? Each element in the budget array is another array?
You'd use a loop.
也许你需要一个矩阵。
在第一个索引中保留预算,在第二个索引中保留五个(在上述情况下)预算项目。
当你有一个矩阵 [x][y] 时,你有 x+1 个数组,每个数组都有 y+1 个元素。
Maybe you need a matrix.
In the first index you keep the budget and in the second index the five (in the case above) budget items.
When you have a matrix [x][y] you have x+1 arrays each of wich with y+1 elements.
数组中有 5 个元素。
您需要二维数组,它基本上是数组的数组。二维数组由两对 [] 声明。在以下示例中,每个
预算
都有 10 个详细信息。There are 5 elements in the array.
You need 2-dimensional array, which is basically an array of array. The 2D array is declared by 2 pairs of []. In the following example, each
budget
have 10 details.如果我理解正确的话,你想要一个类似于...的二维数组,
可以通过以下方式访问:
但这有多不灵活?您必须提前知道每个“类别”将有多少条目,或者具有在添加项目时检查给定数组长度的代码,在需要更大的数组时创建新数组(并复制旧数据)进入其中)。
您可能至少想要的是
ArrayList
的ArrayList
:或者您的
ArrayList
的HashMap
可以通过您的类别名称访问:If I'm understanding you correctly, you want a 2d array that would be something like ...
This could be accessed via:
But how inflexible this is? You have to know in advance how many entries there will be for each "category" or have code that checks a given array length when you're adding an item, creating an new array when you need a larger one (and copying the old data into it).
What you probably want at the very least is a
ArrayList
ofArrayList
s:Or a
HashMap
ofArrayList
s you could access via the names of your categories: