【问题标题】:variable may have not been initialized?变量可能尚未初始化?
【发布时间】:2015-07-04 12:21:56
【问题描述】:

所以在 while 循环中我打印了 ArrayList 存储的一些元素。但是后来当我调用它时,它说数组可能尚未初始化。

有什么想法吗?我正在尝试读取行文件。每行至少有 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;
    }
}

【问题讨论】:

  • 文件为空怎么办?那么store 会是什么呢?

标签: java file-io arraylist


【解决方案1】:
store = new ArrayList<>();

此行在 while 中的每次传递时重新初始化存储。您可能希望在 while 之前对其进行初始化,以便在循环时进行累积。

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

【讨论】:

    【解决方案2】:

    有两种情况可以不初始化:

    1. NoSuchElementException 异常在您的 try 块中引发,在这种情况下您的 catch 块被执行,并且 store 未初始化。我建议从catch 块中选择return,或者将String x = 行移到try 块内。

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

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

    【讨论】:

      猜你喜欢
      • 2012-03-25
      • 1970-01-01
      • 2013-11-24
      • 2016-05-14
      相关资源
      最近更新 更多