如何解决如何将这些代码改进为面向对象的编程?
我想将此代码改进为Java中的OOP。例如,如何从变量avg返回值或如何将ArrayList放在方法参数中?
提前谢谢
class ArrayTester {
private double sum;
public void getAverageNotes() {
List < Integer > theBigList = new ArrayList < Integer > ();
Random theGenerator = new Random();
for (int n = 0; n < 4; n++) {
theBigList.add(theGenerator.nextInt(6) + 1);
}
if (theBigList.size() > 2) {
int max = Collections.max(theBigList);
int min = Collections.min(theBigList);
theBigList.remove(Integer.valueOf(max));
theBigList.remove(Integer.valueOf(min));
System.out.println(theBigList);
for (int n = 0; n < theBigList.size(); n++) {
System.out.println("New note " + n + " of the Informatics is: " + theBigList.get(n));
sum = sum + theBigList.get(n);
}
System.out.println("Collection size is: " + theBigList.size() + "\nExtreme values are: " + min + " and " + max);
double avg = Math.round(sum) / (double) theBigList.size();
System.out.println("Average: " + String.format("%.2f",avg));
} else {
System.out.println("to small");
}
解决方法
您可以通过计算平均值后返回平均值来返回平均值。如果少于2个项目,结果将返回-1。
public double getAverageNotes() {
List<Integer> theBigList = new ArrayList<Integer>();
Random theGenerator = new Random();
for (int n = 0; n < 4; n++) {
theBigList.add(theGenerator.nextInt(6) + 1);
}
if (theBigList.size() > 2) {
double avg = 0;
int max = Collections.max(theBigList);
int min = Collections.min(theBigList);
theBigList.remove(Integer.valueOf(max));
theBigList.remove(Integer.valueOf(min));
System.out.println(theBigList);
int sum = 0;
for (int n = 0; n < theBigList.size(); n++) {
System.out.println("New note " + n + " of the Informatics is: " + theBigList.get(n));
sum = sum + theBigList.get(n);
}
System.out.println("Collection size is: " + theBigList.size() + "\nExtreme values are: " + min + " and " + max);
avg = Math.round(sum) / (double) theBigList.size();
System.out.println("Average: " + String.format("%.2f",avg));
return avg;
} else {
System.out.println("to small");
return -1;
}
}
或者,如果您想将ArrayList用作参数,则可以更改方法签名:
public double getAverageNotes(List<Integer> list){
List<Integer> theBigList = list;
...
并定义要传入的数组列表:
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
Random theGenerator = new Random();
for (int n = 0; n < 4; n++) {
list.add(theGenerator.nextInt(6) + 1);
}
System.out.println(getAverageNotes(list));
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。