list.add不能与ArrayList一起工作

问题描述:

我想从文件中将整数添加到ArrayList和list.add不想工作。我只尝试了大约一千种不同的方式来编写这段代码。该list.add(s.next());行给出了在Eclipse中的错误,list.add不能与ArrayList一起工作

The method add(Integer) in the type List<Integer> is not applicable for the arguments (String).

听起来像我莫名其妙地试图做只能用一个字符串来完成一个整数的东西,但我需要他们保持整数如果在过去的5天里我一直没有用Java搜索,学习和掌握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); 
     } 
    } 

} 
+6

'扫描器#next()'返回一个字符串,你想扫描器#nextInt() 。这还需要一些更具体的文件处理('hasNextInt()'),并根据你的txt文件的格式跳过新行。 – 2013-05-06 14:31:12

您正尝试将String增加的Integer的List。

s.next()返回下一个标记为一个字符串,它不能被添加到整数的列表明显。

+0

感谢您的帮助,这就是诀窍!我觉得我的头埋在书本里太久了,只是被烧毁了。感谢帮助我抓住明显的! – 2013-05-06 16:26:02

s.next()指返回String类型的方法。由于Java是强类型的,因此必须从用户返回一个整数或int类型。 s.nextInt()将工作得很好。

+0

感谢所有的帮助,这就是诀窍! 我想我的头埋在书本里太久了,只是被烧毁了。感谢帮助我抓住明显的! – 2013-05-06 16:10:04

尝试:

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(返回整数而不是字符串) 对不起,我的英语不好

+0

感谢所有的帮助,这就是诀窍! 我想我的头埋在书本里太久了,只是被烧毁了。感谢帮助我抓住明显的! – 2013-05-06 16:09:45