如何将名称列表扫描到数组中?

时间:2014-12-03 22:07:55

标签: java arrays string

我正在尝试扫描200个名称的文件以扫描成一维数组。然后在稍后从阵列访问它们以选择胜利者。但是,我开始时将名称扫描到数组中而丢失了。这是我到目前为止所做的。

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
  }

我很确定这是100%错误,并且认为可能需要类似迭代器的东西,但我在迭代器上有点丢失。有人可以帮我指出正确的方向或解释我做错了什么?

2 个答案:

答案 0 :(得分:3)

您必须将String存储在数组中。您可以使用索引来执行此操作:

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
}

但有些(大部分)时间你不知道需要存储多少元素。在这种情况下,最好使用List而不是数组。 List允许添加元素并调整幕后使用的数据结构。这是一个例子:

List<String> names = new ArrayList<String>();
Scanner playerNamesScan = ...
while(playerNamesScan.hasNextLine() && index < theList.length) {
    String name = playerNamesScan.nextLine(); 
    names.add(name);
}

答案 1 :(得分:0)

您可以使用以下内容;

   int size = 3;  
   List<String> nameList = new ArrayList(); //initializing the size of the array

   //Scan in all names in file.
   Scanner playerNamesScan = new Scanner(new File("c:/temp/PlayerNames.txt"));
   while(playerNamesScan.hasNextLine())
   {
      nameList.add(playerNamesScan.nextLine()); 
   }        

   String[] nameArray = nameList.toArray(new String[nameList.size()]);
   System.out.print(Arrays.toString(nameArray));