有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

线程“main”java中出现异常。尝试更新文件时出现lang.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) 个答案

  1. # 1 楼答案

    问题在于:

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

    我建议你先拿一些样本值来做这件事

    可以使用StringTokenizer来执行此操作

  2. # 2 楼答案

    当您将信息输入到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 loop1开始,进入c。因此,您缺少第一个元素,并试图从null索引中添加一个元素,因此出现了`NullPointerexception

        // Output to user
        for (int i = 1; i <= c; i++){
            //code
        }   
    

    for loop更改为start和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();
            }
        }