从CSV创建对象数组

时间:2015-02-16 23:39:55

标签: java arrays loops csv

所以我在我读过的CSV文件中有一些文字并确保通过打印它们来准确读入它们,但是我仍然坚持如何将它们分开并分配给每个文件。到数组中的特定对象。我在for循环中有15个的原因是因为我需要从我的CSV文件中创建15个不同的Card个对象。

问题:如何创建我已解析并读入的多个Card个对象的数组?

public class Driver {
public static void main(String[] args) throws FileNotFoundException {

    Scanner scan = new Scanner(System.in);
    int numberOfPlayers;
    int playerNumber;

    //reads in Cards.txt
    File cards = new File("./src/Cards.txt");
    Scanner fileScanner = new Scanner(cards);

for(int i = 0; i < 15; i++)
{
    //while there is a new line in the data, goes to the next one
    while(fileScanner.hasNextLine())
    {
        String line = fileScanner.nextLine();
        Scanner lineScanner = new Scanner(line);
        lineScanner.useDelimiter(", ");

        //while there is a new attribute to read in on a given line, reads data
        while(lineScanner.hasNext())
        {
            String cardType = lineScanner.next(); 
            String message = lineScanner.next();
            Double amount = lineScanner.nextDouble();

            //creates a Card
            Card myCard = new Card(cardType, message, amount);
            Card myCards[] = new Card[i]; //stuck here

1 个答案:

答案 0 :(得分:0)

您需要在循环外定义数组,然后在循环内添加它。

在循环之前,你可以拥有

Card[] myCards = new Card[15];

然后在你的循环中你可以拥有

//creates a card
Card myCard = new Card(cardType, message, amount);
myCards[i] = myCard;

您还需要更改循环的结构。第一个while循环将读取文件中的每一行,第二个将读取该行中的每个卡,这实际上不是你想要的。你想每循环读一张卡。此代码应如下所示

Card[] myCards = new Card[15];
// only run this if the file has at least 1 line, and only run once
if (fileScanner.hasNextLine())
{
    String line = fileScanner.nextLine();
    Scanner lineScanner = new Scanner(line);
    lineScanner.useDelimiter(", ");

    for(int i = 0; i < 15; i++)
    {

        // read in one card
        if (lineScanner.hasNext())
        {
            String cardType = lineScanner.next();
            String message = lineScanner.next();
            Double amount = lineScanner.nextDouble();

            //creates a card
            Card myCard = new Card(cardType, message, amount);
            myCards[i] = myCard;
        }
    }
}

查看Oracle的阵列文档,了解如何使用数组获取更多信息http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html

如果某些内容发生变化且您不知道您将拥有多少张卡片,请使用ArrayList代替 http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html