变量可能未被初始化?

3
在 while 循环中,我打印了 ArrayList Store 的一些元素。但是之后当我调用它时,它说数组可能没有被初始化。
有什么想法吗?我正在尝试读取一系列行的文件。每行至少有 8 个元素,我确定数组不为空,因为我在 while 循环中从它打印出来了。
public class ReaderFile {
    public static Scanner input;
    public static Scanner input2;

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        int count=0;
        ArrayList<Team> store;
        ArrayList<Robot> store2;
        //Robot robot;

        String fileLocation = "Tourney2Teams.csv";
        String fileLocation2 = "Tourney1robots.csv";


        try{
            input = new Scanner(new File(fileLocation)).useDelimiter(",");
        }
        catch (IOException ioException)
        {
            System.out.print("PROBLEM");
        }


        try {
            input2 = new Scanner(new File (fileLocation2)).useDelimiter(",");
        }
        catch (IOException ioException)
        {
            System.out.print("problem with robot");
        }


        try{
                input.nextLine();
                System.out.print("PLEAse\n");
                int countt = 0;
                while(input.hasNext())
                {
                        //int countt = 0;
                        int ID = input.nextInt();
                        String teamName = input.next();
                        String coachFirst = input.next();
                        String coachLast = input.next();
                        String mentorFirst = input.next();
                        String mentorLast = input.next();
                        String teamFs = input.next();
                        String teamSS = input.next();
                        input.nextLine();
                        store = new ArrayList<>();
                        Team team = new Team (teamName, ID, coachFirst, coachLast,mentorFirst,mentorLast,teamFs,teamSS);
                        store.add(team);
                        System.out.print("Team Numer"+store.get(0).teamNumber+"\n");
                        countt = countt+1;
                        System.out.print("\n"+countt);
                }
        }
        catch (NoSuchElementException statExcemtion)
        {
            System.out.print("\nAnkosh");
        }
        String x = store.get(2).teamName;
    }
}

1
如果文件是空的呢?那么 store 会变成什么? - Radiodef
2个回答

0
store = new ArrayList<>();

这行代码在每次 while 循环中重新初始化存储。你可能想在 while 之前初始化它以便在循环时累加。

它说未初始化是因为由于某种原因它从未执行过 while 循环(输入为空)。


0

它可以在两种情况下未初始化:

  1. 在您的try块中抛出NoSuchElementException异常,此时执行catch块,并且store未初始化。我建议从catch块中return,或将String x =行移至try块内。

  2. 您的循环没有进行任何迭代。在这种情况下,store也未初始化。这看起来像是一个逻辑错误,您可能希望在while循环之前实例化store

我还建议在访问元素2之前检查store是否至少有三个元素。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接