0

我正在使用扫描仪用数据填充数组。它似乎有效,因为当我在“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
4

2 回答 2

1

您在 for 循环中执行此操作。我认为这不会产生预期的结果。本质上,您将名称分配给同一个玩家,而扫描仪拥有下一个。将它从 for 循环中取出,然后将 i++ 的 while 循环作为循环的最后一个。

于 2012-05-14T03:40:00.187 回答
1

你正在做这个 10 倍(对于每个 i):

 // 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++;
    }
}
于 2012-05-14T03:41:30.703 回答