【问题标题】:Using String Array and Printfile Output getting NullPointerException?使用字符串数组和打印文件输出得到 NullPointerException?
【发布时间】:2017-04-04 18:38:56
【问题描述】:

所以,我正在编写一个程序,其中我需要有一个循环“读取存储在数组的每个元素中的字符串的第一个字符并将其写入输出文件”。

我在以下位置不断收到 NullPointerException:a = planets[i].charAt(0);

 String[] planets = new String[8];
    char a = 'a';

    String pl = "planets.txt";
    File file = new File(pl);
    Scanner inputFile = new Scanner(file);

    for(int i = 0; i < planets.length; i++){
        while(inputFile.hasNext()){
            planets[i] = inputFile.nextLine();
        }
    }
    inputFile.close();

    System.out.println("closed.");

    String b = "planetfirst.txt";
    PrintWriter outputFile = new PrintWriter(b);

    for (int i = 0; i< planets.length; i++){

        a = planets[i].charAt(0);

        outputFile.println(a);
    }


    outputFile.close();
    System.out.println("Data written to the file.");

提前致谢!

编辑: 我为某些上下文添加了程序的其余部分:)

【问题讨论】:

  • 好吧,您的数组中填充了空字符串。第一个索引处没有字符 - 因此是 NullPointerException
  • planets[i] 中什么都没有
  • planets 指的是 8 个 null 值。所以你需要在调用charAt()之前对其进行初始化
  • 现在完全不同了。你不能像那样从你的程序中删除行。
  • @Gendarme 对此感到抱歉! (网站新手)

标签: java arrays nullpointerexception


【解决方案1】:

您的 while 循环在您的 for 循环内,因此所有文本都将在 planets[0] 内,而其余索引将为空(即 null)。当您稍后使用

遍历数组时
for(int i = 0; i < planets.length; i++) {
    a = planets[i].charAt(0);
}

i 大于 0 时,你会得到一个NullPointerException

如果你的文本文件有 8 行,那么就不需要 while 循环,因为你有一个迭代 8 次的 for 循环和一个长度为 8 的数组。

但是,如果文本文件中的行数不同,则不应使用数组,而应使用数组列表,而不是 for 循环,而只有 while 循环。

类似

List<String> planets = new ArrayList<String>();
while(inputFile.hasNext()){
    planets.add(inputFile.nextLine());
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-29
    • 1970-01-01
    • 2011-02-16
    • 2012-08-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多