Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
526 views
in Technique[技术] by (71.8m points)

java - How to scan a list of names into an array?

I am trying to scan a file of 200 names to scan into a one-dimensional array. Then access them from the array at a later point to pick a winner. However, I am lost with the scanning the names into the array to begin with. This is what I have so far.

public static void main(String[] args) throws IOException
{       
   int size = 200;  
   String [] theList = new String[size]; //initializing the size of the array

  //Scan in all names in file.
  Scanner playerNamesScan = new Scanner(new File("PlayerNames.txt"));

  String names; 
  while(playerNamesScan.hasNextLine())
  {
     names = playerNamesScan.nextLine(); 
     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
  }

I am pretty sure this is 100% wrong and think maybe something like an iterator is needed but I am somewhat lost on iterators. Can someone help point me in the right direction or explain what I am doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have to store the Strings 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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...