NullPointerException从文件中读取数组元素-Java

问题描述 投票:0回答:2

在我的程序中,我创建一个景点并填写票证类型的数量,标题和费用,然后退出程序并再次运行。

我有一个从文件中读取元素的构造函数。然后,当我尝试读取数组元素时,即使该元素不为null,它也会给我一个NullPointerException错误。

[当我注释掉错误所在的代码块时,输入字符串“ Tour Only”出现了NumberFormatException错误,所以我知道它不为空。

fileScanner.nextLine();
for (int i = 0; i < getTicketTypesNum(); i++)
    this.ticketTypeTitle[i] = fileScanner.nextLine();
fileScanner.nextLine();

完整代码如下。

Attraction.java

// The constructor.
public Attraction(Scanner fileScanner) {
  ...

  // The data read before the error.
  fileScanner.nextLine();
  this.ticketTypesNum = Integer.parseInt(fileScanner.nextLine());
  fileScanner.nextLine();

  fileScanner.nextLine();
  for (int i = 0; i < getTicketTypesNum(); i++) {
    // Line where the error is located.
    this.ticketTypeTitle[i] = fileScanner.nextLine();
  }

  fileScanner.nextLine();
  for (int i = 0; i < getTicketTypesNum(); i++)
     this.ticketTypeCost[i] = Integer.parseInt(fileScanner.nextLine());
  fileScanner.nextLine();

  ...
}


// Store the attraction information and write it to file.
public void writeData(PrintWriter pw) {
  ...

  pw.println("Number of Ticket Types:");
  pw.println(getTicketTypesNum());
  pw.println();

  pw.println("Ticket Titles:");
  for (int i = 0; i < getTicketTypesNum(); i++)
    pw.println(getTicketTypeTitle()[i]);
  pw.println();

  pw.println("Ticket Costs:");
  for (int i = 0; i < getTicketTypesNum(); i++)
    pw.println(getTicketTypeCost()[i]);
  pw.println();

  ...
}

如果您需要更多代码,我将编辑问题以包括更多内容。

谢谢您的帮助!

UPDATE

我尝试注释掉发生错误的行,并继续运行代码,每当必须读取数组元素时,我都会收到NullPointerException。

java nullpointerexception
2个回答
0
投票

使用fileScanner.hasNextLine()之前,您应先检查fileScanner.nextLine()


0
投票

这是有效的示例程序。您可以尝试这样做并打印阵列。从文件中获取元素之前,请确保已进行此[[scanner.hasNextLine()检查。同样,理想情况下,数组大小应等于文件中占用的行数。

import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Scanner; public class FileRead { public static void main(String args[]) { String array[] = new String[6]; File file = new File("C:\\Users\\Desktop\\text"); try (Scanner sc = new Scanner(file, StandardCharsets.UTF_8.name())) { int i =0; while (sc.hasNextLine()) { array[i] = sc.nextLine(); i++; } } catch (IOException e) { e.printStackTrace(); } System.out.println(Arrays.toString(array)); } }
让我知道这是否适合您。
© www.soinside.com 2019 - 2024. All rights reserved.