首页 > 解决方案 > 我不认为我的数组正在存储和数据

问题描述

我是 Java 新手,现在正在上大学课程。我只是好奇我缺少什么来给自己一个输出,因为现在控制台是空白的。

public static void main(String[] args) throws IOException {

    double avgScore;
    int highestScore, count = 0;
    String highScoringStudent;

    String names[] = null;
    int scores[] = null;

    File myFile = new File("Student_Data.txt");
    Scanner inFile = new Scanner(myFile);

    inFile.nextLine();

    while(inFile.hasNext()) {

        for(int i = 0; i > 0; i++) {
            names[i] = inFile.next();
            scores[i] = inFile.nextInt();
            count++;
        }
    }

    System.out.print("Name             Score");
    System.out.print(names[count] + "             " + scores[count]);
}

标签: javaarrays

解决方案


首先,我真的不建议将 afor放在while循环内,尤其是在这种情况下(因为它不起作用)。以下是问题:

1)您的for循环从i = 0开始,并立即结束,因为!(i > 0) (i is not > 0) - 所以你是对的,没有数据将存储在数组中!

2)在你的for循环中,你正在读取一个字符串,然后一个一个地读取一个 int。阅读完它们后,您应该移动到下一个字符串和整数以存储在namesand的下一个位置score

3)您没有增加 i: 所以(如果 ifor正在工作),您只需在同一位置继续为数组分配不同的值(基本上每次都重置变量的值)。

这将是最适合您的情况的代码:

int i = 0;

while(inFile.hasNext()) {
   names[i] = inFile.next();
   scores[i] = inFile.nextInt();
   count++;
   i++;
}

希望这有帮助!:)


推荐阅读