变量可能尚未初始化?

时间:2015-04-26 00:09:29

标签: java file-io arraylist

所以在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;
    }
}

2 个答案:

答案 0 :(得分:0)

store = new ArrayList<>();

此行在while的每次传递中重新初始化商店。您可能希望在while之前初始化它以在循环时累积。

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

答案 1 :(得分:0)

在两种情况下可以取消初始化:

  1. 在您的try块中抛出NoSuchElementException异常,在这种情况下执行catch块,并且store未初始化。我建议return阻止来自catch,或将String x =行移到try阻止内。

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

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