gpt4 book ai didi

Java数组变量显示为空?

转载 作者:行者123 更新时间:2023-12-02 07:47:59 25 4
gpt4 key购买 nike

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

最佳答案

您将执行此操作 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++;
}
}

关于Java数组变量显示为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10577240/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com