我将如何在循环时将两个元素添加到二维数组中。
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
我将如何在循环时将两个元素添加到二维数组中。
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
在我看来,您想知道每个年级出现的次数。我认为你最好的选择是 HashMap:
Map<Integer, Integer> frequencyTable = new HashMap<Integer, Integer>();
for (Integer grade : gradeArray) {
if (!frequencyTable.containsKey(grade)) {
frequencyTable.put(grade, Collections.frequency(gradeArray, grade));
}
}
您的新编辑仍然让我感到困惑,但这就是我认为您要问的全部内容:
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 的回答的评论:没有任何关于你想要做什么的额外信息,我不得不说这并不是你数据的一个很好的模型。
你不会喜欢的,但方法如下。所以,数组是不可变的。所以,为了避免这个问题,我会使用一个可变的 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> l = new ArrayList>(); 如果你想 :)
希望这有帮助!
只需使用 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");
}
}