数组返回空值

时间:2015-05-10 19:32:59

标签: java arrays

我对Arrays感到有些困惑,并希望有人可以帮助我。

我希望这是有道理的,因为我有点困惑。非常感谢任何帮助!

while循环在'League'类中创建对象

     while (lineScanner.hasNextLine())
       {
       currentLine = lineScanner.nextLine();
           String[] newSSs = currentLine.split(","); 
           Team team = new Team(newSS[0]);
           team.setWins(Integer.valueOf(newSS[1]));
           team.setDraws(Integer.valueOf(newSS[2]));
           team.setLoses(Integer.valueOf(newSS[3]));
           team.setPoints(team.calculatePoints());

4 个答案:

答案 0 :(得分:1)

我想我知道你要做什么...... 在while循环之前创建一个ArrayList(您需要某种类型的集合来存储已解析的团队):

private ArrayList<Team> teams = new ArrayList<Team>();

while (lineScanner.hasNextLine()){
    currentLine = lineScanner.nextLine();
    String[] newSSs = currentLine.split(","); 
    Team team = new Team(newSS[0]);
    team.setWins(Integer.valueOf(newSS[1]));
    team.setDraws(Integer.valueOf(newSS[2]));
    team.setLoses(Integer.valueOf(newSS[3]));
    team.setPoints(team.calculatePoints());
}

你真的只有一个阵列 - 一个拥有球队的阵列。 newSSs的生命周期限制为一次通过循环,一旦lineScanner没有更多的行处理,循环结束并且newSSs被处理掉。

我希望它有所帮助

答案 1 :(得分:1)

我在猜测:

  ArrayList<Team> list = new ArrayList<Team>();
  for(int i=0;i<5;i++)
     list.add(null);

   //change values
    list.set(0,new Team(newSS[0]);
    list.get(0).setWins(Integer.valueOf(newSS[1]));

答案 2 :(得分:0)

我认为你的Team类有以下方法 -

setWins()
setDraws()
setLoses()
setPoints()  

但是在这里你试图使用这些方法形成一个你声明为数组的Team team -

Team team = new Team(newSS[0]); 

由于此处teamTeam的数组,因此尝试执行此操作 -

team[0].setWins(Integer.valueOf(newSS[1]));
team[0].setDraws(Integer.valueOf(newSS[2]));
team[0].setLoses(Integer.valueOf(newSS[3]));

答案 3 :(得分:0)

从代码片段中,您似乎希望将团队详细信息存储在Team对象中。但是,您有许多Team对象,并且您需要它们的数组。这很接近:

ArrayList<Team> teamList = new ArrayList<Team>();
while (lineScanner.hasNextLine())
   {
   currentLine = lineScanner.nextLine();
       String[] newSSs = currentLine.split(","); 
       Team team = new Team(newSS[0]);
       team.setWins(Integer.valueOf(newSS[1]));
       team.setDraws(Integer.valueOf(newSS[2]));
       team.setLoses(Integer.valueOf(newSS[3]));
       team.setPoints(team.calculatePoints());
teamList.add(team);
}

Java 7 ArrayList Java 8 ArrayList