【问题标题】:Copying Data from split text into main data storage arrays is returning 'exception in thread "main" java.lang.NullPointerException [duplicate]将数据从拆分文本复制到主数据存储数组中返回“线程“主”java.lang.NullPointerException中的异常[重复]
【发布时间】:2016-01-05 23:58:48
【问题描述】:

这是我的代码示例,一切似乎都在处理输入数据,但是当尝试将输入数据导出到输出时,代码返回错误:

“线程“主”中的异常 java.lang.NullPointerException 在 JavaProject.main(JavaProject.java:50)"

我已经附上了它的外观和错误的 gyazo 快照:

import java.util.Scanner;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;

public class JavaProject {

    private static char[] input;

    @SuppressWarnings("null")
    public static void main(String[] args) {

        int hrs, mins;
        int[] gameCount;
        int[] MinutesPlayed = null;
        String GamerName, GamerReport;

        //Main data storage arrays
        String[] GameNames = new String[100];
        int[] HighScores = new int[100];


        Scanner Scan = new Scanner(System.in);

        //formatting for output and input
        System.out.println("////// Game Score Report Generator \\\\\\\\\\\\");
        System.out.println("     ");

        //user enters name and then moves to next line
        System.out.println("Enter Your Name");
        GamerName = Scan.nextLine();

        //user is given an example of input format 
        System.out.println("Input Gamer Information " + "Using Format --> Game : Achievement Score : Minutes Played");
        System.out.println("    ");


        System.out.println("Game : Achievement Score : Minutes Played");
        GamerReport = Scan.nextLine();


        String[] splitUpReport; // an array of string
        splitUpReport = GamerReport.split(":"); // split the text up on the colon

        int i = 1;

        //copy data from split text into main data storage arrays 
        GameNames[i] = splitUpReport[0];
        HighScores[i] = Integer.parseInt(splitUpReport[1].trim() );
        MinutesPlayed[i] = Integer.parseInt(splitUpReport[2].trim());

        //output to file 

        try
        {
            FileWriter writer = new FileWriter("output.txt");
            writer.write(GamerReport);
            writer.close();
        } catch (IOException e)
        {
            System.err.println("File does not exist!");
        }

【问题讨论】:

  • 附带说明,java 变量应该采用驼峰命名法。很难阅读您的代码,因为 MinutesPlayed 格式等应该用于类名。

标签: java arrays exception nullpointerexception


【解决方案1】:

这一行:

MinutesPlayed[i] = Integer.parseInt(splitUpReport[2].trim());

给你java.lang.NullPointerException,因为数组没有初始化试试这样:

 int[] MinutesPlayed = new int[100];

而不是int[] MinutesPlayed = null;

【讨论】:

    【解决方案2】:

    这永远不会初始化int[] MinutesPlayed = null;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多