Java数组变量显示为null?

时间:2012-05-14 03:34:21

标签: java arrays null

我正在使用扫描程序用数据填充数组。它似乎有效,因为当我在“if”语句中打印(player [i] .Name)时会打印一个值。但是当我尝试在语句之外打印此值(players [1] .Name)时,它会给出一个空值。

int i = 0;
        while (scanner.hasNextLine()) {
                if (scanner.hasNext()) {
                players[i].Name = scanner.next();
                System.out.println(players[i].Name);
                }
                if (scanner.hasNext()) {
                players[i].Position = scanner.next();
                System.out.println(players[i].Position);
                }
                if (scanner.hasNext()) {
                players[i].Height = scanner.next();
                System.out.println(players[i].Height);
                }
                 if (scanner.hasNext()) {
                players[i].Weight = scanner.next();
                System.out.println(players[i].Weight);
                }
               i++;      
            }//end while

2 个答案:

答案 0 :(得分:1)

你在for循环中这样做。我不认为这会产生预期的结果。基本上,您在下一次扫描仪时将名称分配给同一个播放器。将它从for循环中取出,然后使用i ++作为循环的最后一个循环。

答案 1 :(得分:1)

你正在做这个10倍(每个我):

 // Get all possible scanner entries for all possible lines for i=0
 while (scanner.hasNextLine()) {
        if (scanner.hasNext()) {
            players[i].Name = scanner.next();
 // .. then repeat getting all scanner entries for all lines for i=1...

也许这就是你的意思:

int i = 0;
while (scanner.hasNextLine()) {
    if (scanner.hasNext()) {
        players[i].Name = scanner.next();
        System.out.println(players[i].Name);
        i++;
    }
}

或者甚至可以这样:

int i = 0;
while (scanner.hasNextLine()) {
    while (scanner.hasNext()) {
        players[i].Name = scanner.next();
        System.out.println(players[i].Name);
        i++;
    }
}

或者这个:

int i = 0;
while ((i < 10) && scanner.hasNextLine()) {
    while ((i < 10) && scanner.hasNext()) {
        players[i].Name = scanner.next();
        System.out.println(players[i].Name);
        i++;
    }
}