[英]Why is my code returning value of 'null' from a nested JSON array
[英]Array returning null value
我對Arrays感到有些困惑,希望有人可以幫助我。
我希望這是有道理的,因為我有些困惑。 任何幫助深表感謝!
while循環在“聯盟”類中創建對象
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());
我想我知道您要做什么...在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());
}
您實際上只有一個陣列-一個可容納團隊的陣列。 newSS的生命周期僅限於循環一次,一旦lineScanner沒有更多要處理的行,則循環結束,並丟棄newSS。
希望對您有所幫助
我猜:
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]));
我認為您的Team類具有以下方法-
setWins()
setDraws()
setLoses()
setPoints()
但是在這里,您嘗試使用這些方法組成一個已聲明為數組的Team team
team-
Team team = new Team(newSS[0]);
由於此處的team
是一系列Team
嘗試執行以下操作-
team[0].setWins(Integer.valueOf(newSS[1]));
team[0].setDraws(Integer.valueOf(newSS[2]));
team[0].setLoses(Integer.valueOf(newSS[3]));
從代碼片段來看,您似乎希望將團隊詳細信息存儲在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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.