如何在循环时将两个元素添加到2D数组中。
for(...){
gradeArray[i][i] (gradeArray[95][5] <---- i = 0, gets the zero term for the grade and frequency
gradeArray[i][i] (gradeArray[96][2] <-----i = 1; gets the first term for the grade and frequency
答案 0 :(得分:5)
在我看来,你想知道每个年级发生的次数。我认为你最好的选择是HashMap:
Map<Integer, Integer> frequencyTable = new HashMap<Integer, Integer>();
for (Integer grade : gradeArray) {
if (!frequencyTable.containsKey(grade)) {
frequencyTable.put(grade, Collections.frequency(gradeArray, grade));
}
}
答案 1 :(得分:1)
您的新编辑仍然让我感到困惑,但这就是我能想到的所有问题:
int[][] gradesAndFrequencies = new int[gradeCount][2];
for (int i = minGrade; i < maxGrade; i++) {
int grade = ?;
int frequency = ?;
gradesAndFrequencies[i][0] = grade;
gradesAndFrequencies[i][1] = frequency;
}
这假设您知道总共有多少等级,您知道如何找到每个等级及其频率。
我仍然支持我之前对Ted Hopp回答的评论:如果没有任何关于你想要做什么的额外信息,我不得不说这不是你数据的好模型。
答案 2 :(得分:0)
你不会喜欢它,但这是怎么回事。 因此,数组是不可变的。所以,为了避免这个问题,我会使用一个可变的ArrayList。但要回答你的问题(假设尺寸为95x95):
int newGradeArray[][] = new int[96][96]; //creating a new array that has an extra column and row, for more space.
for(int i = 0; i < 95; i++)//a set of nested loops taking everything from the old array, and moving it to this new one.
for(int j = 0; j < 95; j++)
newGradeArray[i][j] = gradeArray[i][j]
//now to add the elements (in the new element or column, your choice)
newGradeArray[95][95] = 95; //assigns the very edge of the new array a value of 95
或者,您可以使用ArrayList。 这样,您不需要创建新数组并重新分配,您可以执行以下操作:
ArrayList<Integer> a = new ArrayList<Integer>(); //note: ArrayLists can only have classes, not primitive types. Luckily, Integer and I think Character are classes too!
a.add(95, new Integer(95)); //sets the index of 95 as an Integer: 95.
这些可以是二维的。 或者:
ArrayList<int[]> i = new ArrayList<int[]>();
甚至: 的ArrayList&GT; l = new ArrayList&gt;(); 如果你想:)
希望这有帮助!
答案 3 :(得分:-3)
只使用2个列表,一个用于成绩,一个用于频率
使用:
List<Integer> grades = new ArrayList<Integer>();
List<Integer> freq = new ArrayList<Integer>();
grades.add(grade);
freq.add(frequency);
添加到他们
这会更简单。
示例:
while(1 == 1) //infinite loop
{
grade = -1
frequency = -1
grade = inputGrade.nextInt();
frequency = inputFrequency.nextInt();
if(grade != -1 && frequency != -1)
{
grades.add(grade);
freq.add(frequency);
}
else
{
//if using a command window
System.out.println("Missing either frequency or grade, values not stored");
//if not using a command window
JOptionPane.showMessageDialog(null, "Missing either frequency or grade, values not stored");
}
}