gpt4 book ai didi

java - 无法迭代传递给方法的列表

转载 作者:行者123 更新时间:2023-11-29 03:00:44 25 4
gpt4 key购买 nike

该程序用于从 ArrayList 中查找缺失的数字。但是,由于以下错误,它无法输出结果:

Type mismatch: cannot convert from element type Object to int

List 在被调用的方法中迭代时发生。类型转换似乎没有帮助。如何纠正?

import java.util.ArrayList;
import java.util.List;
public class FindMisingNumbersInAList {

public static void main(String[] args) {

List<Integer> list = new ArrayList<Integer>();
for (int i = 1; i <= 100; ++i){
list.add(i);
list.remove(new Integer(12));
list.remove(new Integer(79));

Integer[]missing = getTwoMissingNumbers(list);
System.out.println(missing[0]+ "," +missing[1]);

}
}


private static Integer[] getTwoMissingNumbers(List list) {


int n = list.size()+2;
int expectedSum = n*(n+1)/2;
int expectedSquaredSum = n*(n+1)*(2*n+1)/6;
int sum = 0;
int squaredSum = 0;

System.out.println("SIZE :::" +list.size());

for(int num : list)
{
sum = sum + num;
squaredSum = squaredSum + (num*num); }

int xplusy = expectedSum-sum;
int xsquareplusysquare = expectedSquaredSum-squaredSum;
int twoxy = xplusy*xplusy-xsquareplusysquare;
int xminusy = (int)Math.sqrt(xsquareplusysquare-twoxy);
int x = (xplusy+xminusy)/2;
int y = (xplusy-xminusy)/2;

return new Integer[]{x,y};
}

最佳答案

List list 更改您的方法参数至 List<Integer> list :

private static Integer[] getTwoMissingNumbers(List<Integer> list) {
...
}

因为当你通过 List<Integer>作为List , 有一个缩小,并且 Java 丢失了关于列表类型的信息。

关于java - 无法迭代传递给方法的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35169298/

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