无法使用Arraylist.get方法,它显示“不兼容的操作数类型对象和int”
我试图从用户采取未知数量的整数(直到用户输入0),并计数每个输入的整数。我想,在完成整数之后算数,我不得不将它们存储在一个数组中。我做了一些研究并意识到创建一个长度未指定的Array的唯一方法是ArrayList是唯一的方法。但我的代码,这部分显示错误:无法使用Arraylist.get方法,它显示“不兼容的操作数类型对象和int”
import java.util.Scanner;
import java.util.ArrayList;
public class IntegersOccurence {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.print("Enter the integers between 1 and 100: ");
ArrayList list = new ArrayList();
System.out.println(list.get(0));
//eclipse is showing an error in the line right below
while (list.get(list.size() - 1) != 0) {
list.add(input.nextInt());
}
}
}
的话,最好使用此代码:
import java.util.List;
import java.util.Scanner;
import java.util.ArrayList;
public class IntegersOccurence {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.print("Enter the integers between 1 and 100: ");
List<Integer> list = new ArrayList<Integer>();
list.add(input.nextInt());
System.out.println(list.get(0));
//eclipse is showing an error in the line right below
while (list.get(list.size() - 1) != 0) {
list.add(input.nextInt());
}
}
}
您使用raw type
所以列表的类型为Object
不能相比int
(0
),因此使用
ArrayList<Integer> list = new ArrayList<>();
Read , What is a raw type and why shouldn't we use it?
As mentioned:您在中没有添加任何元素和调用get
会导致崩溃,因为
IndexOutOfBoundsException - if the index is out of range (index < 0 ||
index >= size()
这里index>=size()
是真实的(列表的大小为0,没有元素),所以因此例外
更改如下行:
ArrayList list = new ArrayList();
收件人:
ArrayList<Integer> list = new ArrayList<>();
默认情况下,您的列表类型是Object,通过定义数据类型我们避免了运行时类型错误,并且检查在编译时完成。
谢谢!这有助于消除错误!但它仍然显示“线程中的异常”主“” public static void main(String [] args){ \t \t Scanner input = new Scanner(System.in); System.out.print(“输入1到100之间的整数:”);};
\t \t \t \t ArrayList
\t \t boolean val = true;
\t \t而(VAL ==真){
\t \t \t \t \t \t如果(list.get(名单。size() - 1)== 0){
\t \t \t \t val = false;
\t \t \t}
\t \t \t否则{
\t \t \t \t list.add(input.nextInt());
\t \t \t}
\t \t}
\t \t \t \t}
} –
有什么异常?在线程异常 “主” java.lang.ArrayIndexOutOfBoundsException: – HaroldSer
输入整数1到100之间-1 \t在java.util.ArrayList.elementData(未知来源) \t在java.util.ArrayList.get(未知源) \t at IntegersOccurence.main(IntegersOccurence.java:16) –
也许你可以参考[这里](https://stackoverflow.com/questions/18513308/what-is-the-difference-between-arraylist- arraylist-arraylistobject),因为它可以回答你的问题:) – nkpg