尝试更新文件时线程“main”java.lang.NullPointerException中的异常

时间:2014-01-24 00:57:17

标签: java nullpointerexception

我在初学者CS课程中,我正在尝试更新文件中的信息。数组中的信息会暂时被替换;但是,我无法将更改保存到文件中。而且,即使在它被替换之后,我也会收到“null”错误。

这是我的代码,我省略了不相关的行和方法:

     public static void readData(){
    // Variables
    int choice2, location;

    // Read file
    File dataFile = new File("C:/Users/shirley/Documents/cddata.txt");
    FileReader in;
    BufferedReader readFile;

    // Arrays
    String[] code  = new String[100];
    String[] type = new String[100];
    String[] artist = new String[100];
    String[] song = new String[100];
    Double[] price = new Double[100];
    Double[] vSales = new Double[100];

    // Split Variables
    String tempCode, tempType, tempArtist, tempSong, tempPrice, tempVsales;

    // Split
    String text;
    int c = 0;

    try{
        in = new FileReader(dataFile);
        readFile = new BufferedReader(in);
        while ((text = readFile.readLine()) != null){
            // Split line into temp variables
            tempCode = text.substring(0,5);
            tempType = text.substring(5,15);
            tempArtist = text.substring(16,30);
            tempSong = text.substring(30,46);
            tempPrice = text.substring(46,52);
            tempVsales = text.substring(52);

            // Place text in correct arrays
            code[c] = tempCode;
            type[c] = tempType;
            artist[c] = tempArtist;
            song[c] = tempSong;
            price[c] = Double.parseDouble(tempPrice);
            vSales[c] = Double.parseDouble(tempVsales);

            c += 1; // increase counter
        }

        // Output to user
        Scanner kb = new Scanner(System.in);
        System.out.print("\nSelect another number: ");
        choice2 = kb.nextInt();

        // Reads data
        if (choice2 == 5){
            reqStatsSort(code,type,artist,song,price,vSales,c);
            location = reqStatistics(code,type,artist,song,price,vSales,c);
            if (location == -1){
                System.out.println("Sorry, code not found.");
            }
            else{
                System.out.print("Enter new volume sales: ");
                vSales[location] = kb.nextDouble();
            }
            displayBestSellerArray(type,artist,song,vSales,c);

            readFile.close();
            in.close();

            changeVolume(code,type,artist,song,price,vSales,c); // Method to rewrite file
            readData();
        }
    }catch(FileNotFoundException e){
        System.out.println("File does not exist or could not be found.");
        System.err.println("FileNotFoundException: " + e.getMessage());
    }catch(IOException e){
        System.out.println("Problem reading file.");
        System.err.println("IOException: " + e.getMessage());
    }
}










/////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
///////////////// REQ STATS SORT METHOD ////////////////
///////////////////////////////////////////////////////
///////////////////////////////////////////////////////
///////////////////////////////////////////////////////

public static void reqStatsSort(String[] sortCode, String[] sortType, String[] sortArtist, 
        String[] sortSong, Double[] sortPrice, Double[] sortVSales, int c){
    // Variables
    String tempCode, tempArtist, tempType, tempSong;
    double tempVsales, tempPrice;

    for(int j = 0; j < (c - 1); j++){
        for (int k = j + 1; k < c; k++){
            if ((sortCode[k]).compareToIgnoreCase(sortCode[j]) < 0){
                // Switch CODE
                tempCode = sortCode[k];
                sortCode[k] = sortCode[j];
                sortCode[j] = tempCode;

                // Switch TYPE
                tempType = sortType[k];
                sortType[k] = sortType[j];
                sortType[j] = tempType;

                // Switch ARTIST
                tempArtist = sortArtist[k];
                sortArtist[k] = sortArtist[j];
                sortArtist[j] = tempArtist;

                // Switch SONG
                tempSong = sortSong[k];
                sortSong[k] = sortSong[j];
                sortSong[j] = tempSong;

                // Switch VOLUME
                tempVsales = sortVSales[k];
                sortVSales[k] = sortVSales[j];
                sortVSales[j] = tempVsales;

                // Switch PRICE
                tempPrice = sortPrice[k];
                sortPrice[k] = sortPrice[j];
                sortPrice[j] = tempPrice; 
            }
        }

    }
}    










/////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
/////////////// REQUEST STATISTICS METHOD //////////////
///////////////////////////////////////////////////////
///////////////////////////////////////////////////////
///////////////////////////////////////////////////////

public static int reqStatistics(String[] statsCode, String[] statsType,
        String[] statsArtist, String[] statsSong, Double[] statsPrice, 
        Double[] statsVSales, int c){
    // Variables
    String cdCode;

    // Obtain input from user
    Scanner kb = new Scanner(System.in);
    System.out.print("Enter a CD code: ");
    cdCode = kb.nextLine();

    // Binary search
    int position;
    int lowerbound = 0;
    int upperbound = c - 1;

    // Find middle position
    position = (lowerbound + upperbound) / 2;

    while((statsCode[position].compareToIgnoreCase(cdCode) != 0) && (lowerbound <= upperbound)){
        if((statsCode[position].compareToIgnoreCase(cdCode) > 0)){
            upperbound = position - 1;
        }
        else {
            lowerbound = position + 1;
        }
        position = (lowerbound + upperbound) / 2;
    }

    if (lowerbound <= upperbound){
        return(position);
    }
    else {
        return (-1);
    }
}











/////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
/////////////// BEST SELLER ARRAY METHOD //////////////
///////////////////////////////////////////////////////
///////////////////////////////////////////////////////
///////////////////////////////////////////////////////
public static void displayBestSellerArray (String[] displaySortedType, 
        String[] displaySortedArtist, String[] displaySortedSong, 
        Double[] displaySortedVSales, int c){
    // Output to user
    System.out.println();
    System.out.println("MUSIC         ARTIST              HIT SONG            VOLUME");
    System.out.println("TYPE                                                  SALES");
    System.out.println("--------------------------------------------------------------------");
    for (int i = 0; i < c; i++){
        System.out.print(displaySortedType[i] + "   " + displaySortedArtist[i] + "     "
                + displaySortedSong[i] + "     ");
        System.out.format("%6.0f",displaySortedVSales[i]);
        System.out.println();
    }
}












/////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
////////////////// CHANGE VOLUME METHOD ////////////////
///////////////////////////////////////////////////////
///////////////////////////////////////////////////////
///////////////////////////////////////////////////////

public static void changeVolume(String[] writeCode, String[] writeType,
        String[] writeArtist, String[] writeSong, Double[] writePrice,
        Double[] writeVSales, int c){
    File textFile = new File("C:/Users/shirley/Documents/cddata.txt");
    FileWriter out;
    BufferedWriter writeFile;

    // Variables
    String entireRecord, tempVSales;
    int decLoc;

    try{
        out = new FileWriter(textFile);
        writeFile = new BufferedWriter(out);

        // Output to user
        for (int i = 1; i <= c; i++){
            // Convert volume sales to String
            tempVSales = Double.toString(writeVSales[i]);
            // Get rid of decimals
            decLoc = (tempVSales.indexOf("."));
            tempVSales = tempVSales.substring(0,decLoc);
            // Create record line
            entireRecord = writeCode[i] + " " + writeType[i] + " " + writeArtist[i]
                    + " " + writeSong[i] + " " + writePrice[i] + " " + tempVSales;
            // Write record to file
            writeFile.write(entireRecord);
            if (i != c){
                writeFile.newLine();
            }
        }
        writeFile.close();
        out.close();
        System.out.println("Data written to file.");
    }
    catch(IOException e){
        System.out.println("Problem writing to file.");
        System.out.println("IOException: " + e.getMessage());
    }
}

最后一个方法changeVolume()是不起作用的。我得到的错误是

    Exception in thread "main" java.lang.NullPointerException
at culminating3.Culminating3.changeVolume(Culminating3.java:508)
at culminating3.Culminating3.readData(Culminating3.java:185)
at culminating3.Culminating3.readData(Culminating3.java:167)
at culminating3.Culminating3.main(Culminating3.java:47)
    Java Result: 1

第508行是:

                    tempVSales = Double.toString(writeVSales[i]);
在changeVolume方法()中的

因此,我的程序要求用户输入CD代码以更改销售量,并在输入的代码存在时对阵列进行排序以执行二进制搜索。如果是这样,我的程序将替换旧的销售量(它确实如此),并使用changeVolume()方法保存它(它没有这样做并给我错误)。

请记住我是新手。它对我来说很好,但我无法弄清楚为什么它不起作用。我为代码中的任何混乱道歉。 writeVSales []不应为null,因为我在readData()方法中分配了输入?

2 个答案:

答案 0 :(得分:0)

问题出在这里:

       // Convert volume sales to String
        tempVSales = Double.toString(writeVSales[i]);
        // Get rid of decimals
        decLoc = (tempVSales.indexOf("."));
        tempVSales = tempVSales.substring(0,decLoc);

我建议你先拿一些样本值来解决这个问题。

您可以使用StringTokenizer执行此操作。

答案 1 :(得分:0)

当您将信息输入writeVSales数组时,每次添加新项目时都会从0(好)开始并增加c,无论是否有新项目添加与否(再次没问题)。

int c = 0;

try{
    in = new FileReader(dataFile);
    readFile = new BufferedReader(in);
    while ((text = readFile.readLine()) != null){
        // Split line into temp variables
        tempCode = text.substring(0,5);
        tempType = text.substring(5,15);
        tempArtist = text.substring(16,30);
        tempSong = text.substring(30,46);
        tempPrice = text.substring(46,52);
        tempVsales = text.substring(52);

        // Place text in correct arrays
        code[c] = tempCode;
        type[c] = tempType;
        artist[c] = tempArtist;
        song[c] = tempSong;
        price[c] = Double.parseDouble(tempPrice);
        vSales[c] = Double.parseDouble(tempVsales);

        c += 1; // increase counter
    }

稍后changeVolume() for loop 1c开始,然后转到null。所以你缺少第一个元素并尝试从 // Output to user for (int i = 1; i <= c; i++){ //code } 的索引添加一个元素,因此是'NullPointerexception。

for loop

0更改为开始i < c并转到c - 1(即 for (int i = 0; i < c; i++){ // Convert volume sales to String tempVSales = Double.toString(writeVSales[i]); // Get rid of decimals decLoc = (tempVSales.indexOf(".")); tempVSales = tempVSales.substring(0,decLoc); // Create record line entireRecord = writeCode[i] + " " + writeType[i] + " " + writeArtist[i] + " " + writeSong[i] + " " + writePrice[i] + " " + tempVSales; // Write record to file writeFile.write(entireRecord); if (i != c){ writeFile.newLine(); } } ):

{{1}}