从输入文件创建对象

时间:2015-03-21 01:35:36

标签: class object arraylist

我试图以某种方式通过从文本文件中读取来创建对象。但是,我似乎做错了什么,我不能把手指放在上面。

主:

import java.util.*;
import java.io.*;
public class Project2 {

public static void main(String[] args) throws IOException {
    Scanner sc = new Scanner((new File("Project2DataFile.txt")));
    sc.useDelimiter(",");
    ArrayList<BaseballPlayer> myplayer = new ArrayList<BaseballPlayer>();
    while (sc.hasNext()) {
        String str = sc.nextLine();
        for(int cnt = 0; cnt < 4; cnt++){
            BaseballPlayer player = new BaseballPlayer();
            if( player.batavg < 0 || player.batavg > 100 ){throw new IllegalArgumentException ("Illegal Batting Avg");}
            player.pnumber = sc.nextInt();
            player.lastname = sc.next();
            player.firstname = sc.next();
            player.batavg = sc.nextFloat(); 
        }
        continue;
    }

    System.out.println(myplayer);

}

类别:

public class BaseballPlayer {

        public static int pnumber; // player number
        public static String lastname; // player's last name
        public static String firstname; // player's first name
        public static float batavg; // player's batting average
    }

我也可以将文本文件放在那里:

48,deGrom,Jacob,.120
58,Mejia,Jenry,.140
49,Niese,Jon,.091
7,d'Arnaud,Travis,.324
21,Duda,Lucas,.237
4,Flores,Wilmner,.268
11,Tejada,Ruben,.345
5,Wright,David,.289
3,Granderson,Curtis,.327
12,Lagares,Juan,.298

1 个答案:

答案 0 :(得分:0)

您似乎错误地使用了staticstatic适用于所有类实例共享的成员,因此您不应在BaseballPlayer中使用它。要解决此问题,您需要删除static中的所有BaseballPlayer