You have to store the String
s in the array. You can do it by using an index:
int index = 0;
while(playerNamesScan.hasNextLine() && index < theList.length) {
names = playerNamesScan.nextLine();
theList[index++] = names;
System.out.println(names); //just to make sure it is scanning in all the names
System.out.println(theList[0]); //this gives me null because not in array
}
But some (most of the) times you don't know how many elements you need to store. In such cases, it would be better to use a List
rather than an array. A List
allows adding elements and resize the data structure used behind the scenes for you. Here's an example:
List<String> names = new ArrayList<String>();
Scanner playerNamesScan = ...
while(playerNamesScan.hasNextLine() && index < theList.length) {
String name = playerNamesScan.nextLine();
names.add(name);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…