[英]list.add not working with ArrayList
我正在尝试将文件中的整数添加到ArrayList中,并且list.add不想工作。 我只尝试了大约一千种不同的方式来编写此代码。 list.add(s.next());
行在Eclipse中给出错误,
The method add(Integer) in the type List<Integer> is not applicable for the arguments (String).
听起来我在某种程度上试图用只能用字符串完成的整数做某事,但我需要它们保持整数,并且如果我连续五天没有一直在使用Java搜索,研究和学习我的知识,我大概可以理解它的意思。
我可以让它与常规数组一起正常工作,但是我的ArrayList集合确实很痛苦,我不确定自己做错了什么。 任何帮助将非常感激。
提前致谢。
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class MyCollection {
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void main(String[] args) {
List<Integer> list = new ArrayList();
//---- ArrayList 'list'
Scanner s = new Scanner(new File("C:/Users/emissary/Desktop/workspace/stuff/src/numbers.txt"));
while (s.hasNext()) {
list.add(s.next());
}
s.close();
Collections.sort(list);
for (Integer integer : list){
System.out.printf("%s, ", integer);
}
}
}
s.next()
是指返回String
类型的方法。 由于Java是强类型的,因此必须从用户返回整数或int
类型。 s.nextInt()
可以正常工作。
您正在尝试将String
添加到Integer
的列表中。
s.next()
以字符串形式返回下一个标记,显然不能将其添加到整数列表中。
尝试这个:
List<Integer> list = new ArrayList<Integer>();
//---- ArrayList 'list'
Scanner s = new Scanner(new File("C:/Users/emissary/Desktop/workspace/stuff/src/numbers.txt"));
while (s.hasNextInt()) {
list.add(s.nextInt());
}
s.close();
Collections.sort(list);
for (Integer integer : list){
System.out.printf("%s, ", integer);
}
s.hasNextInt()检查来自扫描仪的下一个数据中是否存在整数。 要将整数添加到整数列表中,必须使用nextInt返回一个整数而不是字符串对不起,我的英语不好
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.