Reputation: 415
So right now I am getting an Syntax error when I am trying to use a method that does not return any value (is void), and that takes in arguments ArrayList<E> fileList
. My goal is to take in a text file that has both String, and Integer objects, and in the remove method if it finds a Integer then it will be removed from the list. This is so it will only be leaving the Strings at the end. Here is the code that shows both the reading of the file, and the removeInts
method I am trying to use:
@SuppressWarnings("unchecked") //IDE told me to add this for adding objects to the ArrayList
public <E> ArrayList<E> readFile(){
ArrayList<E> fileList = new ArrayList<E>();
try {
Scanner read = new Scanner(file); //would not let me do this without error handling
while(read.hasNext()){ //while there is still stuff to add it will keep filling up the ArrayList
fileList.add((E)read.next());
}
} catch (FileNotFoundException e) {
System.out.println("File not found!");
e.printStackTrace();
}
removeInts(fileList);
return fileList;
}
public void removeInts(ArrayList<E> fileList){
for(int i = 0; i < fileList.size(); i++){
if(fileList.get(i) instanceof Integer){
fileList.remove(i);
}
else{
//does nothing, does not remove the object if it is a string
}
}
I am getting the syntax error at removeInts(fileList)
.
Upvotes: 0
Views: 58
Reputation: 159135
As others pointed out, your list will never contain an Integer
, because next()
returns a String
.
Given your last comment:
I am trying to be able to remove ints from a text file, only leaving strings left. Say for example I had a text file that said
"A B C 1 2 3"
, first theScanner
(I need to use a scanner) would take in the file, and put it into anArrayList
. Then when I use theremove
method it would take out all values that are Integers, and leave alone the Strings. The final output at the end would be"A B C"
.
Don't first load them as Integer and then remove them. Instead, don't load them:
List<String> list = new ArrayList<>();
try (Scanner sc = new Scanner("A B C 1 2 3")) {
while (sc.hasNext()) {
if (sc.hasNextInt())
sc.nextInt(); // get and discard
else
list.add(sc.next());
}
}
System.out.println(list);
Output
[A, B, C]
Upvotes: 3
Reputation: 17548
Change the signature of removeInts to be generic:
public <E> void removeInts(ArrayList<E> fileList)
Upvotes: 2