I am trying to add integers from a file into an ArrayList and list.add doesn't want to work. I've only tried about a thousand different ways to write this code. The list.add(s.next()); line gives an error in Eclipse,
The method add(Integer) in the type List<Integer> is not applicable for the arguments (String).
Sounds like I am somehow trying to do something with an integer that can only be done with a string, but I need them to remain integers and if I hadn't been searching, studying and cramming my head with Java for the last 5 days straight I could probably understand what it means.
I can get it to work with a regular array just fine, but my ArrayList collection is a real pain and I'm not sure what I'm doing wrong. Any help would be much appreciated.
Thanks in advance.
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);
}
}
}
Scanner#next()returns a String, you wantScanner#nextInt(). This will also require some more specific file handling (hasNextInt()) and skipping new lines depending on your format of your txt file.