gpt4 book ai didi

java - Java ArrayList - 大小为零

转载 作者:行者123 更新时间:2023-12-01 18:57:47 26 4
gpt4 key购买 nike

我的程序(包含在下面)不断出现列表大小为零的错误,这会弄乱其他所有内容。我猜这意味着我没有正确添加元素,但我无法弄清楚它出了什么问题。我在技术上面临挑战,因此很抱歉格式不正确。感谢您的帮助!

import java.util.Scanner;
import java.util.ArrayList;
public class ListStat {
public static void main (String[] args) {
ListStat r = new ListStat();
System.out.println("A default list was created." + r.toString());
ListStat r1 = new ListStat(30);
System.out.println("Another list was created." + r1.toString());
ListStat r2 = new ListStat(40);
System.out.println("Another list was created." + r2.toString());
r1.add(4);
System.out.println("The item at index 13 for r1 is: " + r1.get(13));
System.out.println("r1 and r2 are equal: " + r1.equals(r2));
System.out.println("r1 and r2 overlap this number of times: " + r1.countOverlap(r1, r2));
}

private ArrayList<Integer> list;

public ListStat() {
list = new ArrayList<Integer>();
}

public ListStat(int N) {
list = new ArrayList<Integer>(N);
for (int i=0; i<N; i++) {
list.add(i, i+1);
}
}

public void add(int num) {
list.add(num);
}

public int get(int index) {
return list.get(index);
}

public int getListLength(){
return list.size();
}

public double getMean() {
int sum = 0;
for (int i=0; i<list.size(); i++) {
sum = sum + list.get(i);
}
double mean = sum/list.size();
return mean;
}

public int getSum() {
int sum = 0;
for (int i=0; i<list.size(); i++) {
sum = sum + list.get(i);
}
return sum;
}

public boolean equals(ListStat r) {
if (r.equals(list))
return true;
else
return false;
}

public static int countOverlap(ListStat r1, ListStat r2) {
int count = 0;
for (int i=0; i<r1.getListLength(); i++) {
for (int j=0; j<r2.getListLength(); j++) {
if (r1.get(i)==r2.get(j)) {
count++;
}
}
}
return count;
}

public double getStdDev() {
int sum = 0;
double standardDev = 0.0;
for (int i=0; i<list.size(); i++) {
sum = sum + list.get(i);
}
double mean = sum/list.size();
double standsum=0;
for (int i=0; i<list.size(); i++) {
standardDev = (list.get(i) - mean) * (list.get(i) - mean);
standsum=standsum+standardDev;
}
standsum = standsum/list.size();
standsum = Math.sqrt(standsum);
return standsum;
}

public String toString() {
return "The list length is " + getListLength() + ", the mean is " + getMean() + ", the sum is " + getSum() + ", and the standard deviation is " + getStdDev();
}
}

最佳答案

问题的原因是

double mean = sum / list.size();

在 getMean() 方法中。

  1. 程序创建了一个对象r,该对象为空,表示

    r.size() = 0;

  2. 然后在第9行,调用r.toString()方法,该方法调用getMean()。由于r.size为0,所以程序抛出异常

线程“main”中的异常 java.lang.ArithmeticException:/为零

关于java - Java ArrayList - 大小为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13355008/

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