如何将名称列表扫描到数组中? [英] How to scan a list of names into an array?

查看:132
本文介绍了如何将名称列表扫描到数组中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试扫描200个名称的文件以扫描到一维数组。然后在以后从阵列访问它们以选择获胜者。但是,我迷失了将名称扫描到数组中的开始。

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
  }

我很确定这是100%错误,并认为也许需要类似迭代器的东西,但是我对迭代器有些迷失。有人可以帮助我指出正确的方向或解释我做错了什么吗?

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?

推荐答案

您必须将 String s存储在数组中。您可以通过使用索引来做到这一点:

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
}

),您不知道需要存储多少元素。在这种情况下,最好使用 List 而不是数组。 列表允许您添加元素并调整后台使用的数据结构的大小。例如:

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);
}

这篇关于如何将名称列表扫描到数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆