gpt4 book ai didi

java - 了解 equals 方法的模式和帮助

转载 作者:太空宇宙 更新时间:2023-11-04 14:04:40 24 4
gpt4 key购买 nike

我有 2 个简单问题;这是我的代码。我对该模式方法的工作原理感到困惑(它有效)。我还需要有关 equals 方法的帮助。我是否只需创建另一个数组并查看它们是否相等,我该怎么做?

Public class Grades
{
private int[] grade;
private int highest, mode;
private double average, median;

public Grades(int n)
{
Random r = new Random();
grade = new int[n];
for (int i = 0; i < n; i++)
grade[i] = Math.abs(r.nextInt())%101;
}

public double getTotal()
{
int total = 0;
int i;
for (i = 0; i < grade.length; i++)
total += grade[i];
return total;
}

public void calAverage()
{
average = getTotal()/(double) grade.length;
}

public int getHigh()
{
return highest;
}

public double getMedian()
{
return median;
}

public int getMode()
{
return mode;
}

public double getAverage()
{
return average;
}

public void highest()
{
highest = grade[grade.length - 1];
}

public void sort()
{

int i, j, t;
for (i = 0; i < grade.length - 1; i++)
for (j = i + 1; j < grade.length; j++)
if (grade[i] > grade[j])
{
t = grade[i];
grade[i] = grade[j];
grade[j] = t;
}
}

public void calMedian()
{

if (grade.length%2 == 0)
median = (grade[grade.length/2 - 1] + grade[(grade.length)/2])/2.;
else
median = grade[grade.length/2];
}

public void calMode()
{
int[] a = new int[101];
int i, m;
for (i = 0; i <= grade.length; i++)
a[i] = 0;
for (i = 0; i < grade.length; i++)
a[grade[i]]++;
m = 0;
for (i = 0; i < a.length; i++)
if (a[i] > a[m])
m = i;
mode = m;
}

public String toString()
{
int i;
String s = "";
for (i = 0; i < grade.length; i++)
{
s = s + grade[i] + " ";
if ((i + 1)%10 == 0)
s = s + '\n';
}
return s;
}

}

最佳答案

我已经解释了 mode() 方法,但我不确定您对 equals() 方法有何要求,如果您能澄清,我将更新我的答案以包括对此的解释。

public void calMode()
{
// This array will allow for indexes from 0 to 100
// (the same range as a grade on a 0-100 scale)
int []a=new int[101];

int i,m; // these are just temporary indexes

// You don't need to do this, an int in java is set to 0 by default
// as is an array of ints
for(i=0;i<=grade.length;i++)
a[i]=0;

// Here you are looking at each grade and incrementing the occurrences of each
// where each index is the grade and the value stored at that index is the number
// of times that grade appears
for(i=0;i<grade.length;i++)
a[grade[i]]++;
m=0;

// Here you are finding which grade has the highest frequency (the mode)
// by comparing the values you calculated in the previous loop
for(i=0;i<a.length;i++)
if(a[i]>a[m])
m=i;
mode=m;
}

关于java - 了解 equals 方法的模式和帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28994105/

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