I am trying to insert String
values (using a Scanner
) into an ArrayList
.
I am getting the error:
non-static method add(E) cannot be referenced from a static context.
I assume the add()
method is the problem - what other methods can I use to insert into an ArrayList
that is static?
import java.util.*;
public class Solution {
private static List<String> strings;
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
for(int i = 0; i < 5; i++){
String s = scanner.nextLine();
List.add(s);
}
}
}
You try to add a string to List
interface (add()
method is not static) but should add it to your instance List<String> strings
:
strings.add(s);
Also, you should initialize strings
private static List<String> strings = new ArrayList<>();
otherwise, you will get NullPointerException
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments