0

我在运行我的项目时遇到问题,错误是数组超出范围,你能帮我吗?这是我的方法

public double hitungAkurasi(TrainRecord[] trainRecords, TestRecord[] testRecords, int K) {
    if (K <= 0) {
        System.out.println("K should be larger than 0!");
        return -1;
    }

    //normalisasi
    TrainRecord[] trainingSet = trainRecords;
    TestRecord[] testingSet = testRecords;

    //System.out.println("Test" + testRecords);

    trainingSet = (TrainRecord[]) normalisasi(trainingSet);
    testingSet = (TestRecord[]) normalisasi(testingSet);

    Record[] join = trainingSet;


    //test those TestRecords one by one
    int numOfTestingRecord = testingSet.length;
    int numOfTrainingRecord = trainingSet.length;
    int sumNumOfRecord = numOfTestingRecord + numOfTrainingRecord;

    //train record
    for (int i = 0; i < (sumNumOfRecord) / K; i++){
        TrainRecord[] neighbors = findKNearestNeighbors(trainingSet, testingSet[i], K);
        int classLabel = classify(neighbors);
        testingSet[i].predictedLabel = classLabel; //assign the predicted label to TestRecord
    }
    for (int j = ((numOfTrainingRecord + 1) * sumNumOfRecord) / K; j < sumNumOfRecord; j++){
        TrainRecord[] neighbors = findKNearestNeighbors(trainingSet, testingSet[j], K);
        int classLabel = classify(neighbors);
        testingSet[j].predictedLabel = classLabel; //assign the predicted label to TestRecord
    }

    //test record
    for (int t = (numOfTestingRecord * sumNumOfRecord) / K; t < ((numOfTestingRecord + 1) * sumNumOfRecord) / K; t++){
        TrainRecord[] neighbors = findKNearestNeighbors(trainingSet, testingSet[t], K);
        int classLabel = classify(neighbors);
        testingSet[t].predictedLabel = classLabel; //assign the predicted label to TestRecord
    }

    int correctPrediction = 0;
    for (int l = 0; l < numOfTestingRecord; l++) {

        if (testingSet[l].predictedLabel == testingSet[l].classLabel) {
            correctPrediction++;
        }
    }

    return ((double) correctPrediction / numOfTestingRecord) * 100;
}

当我尝试禁用循环程序成功成功的测试记录时,但是当我启用该循环时,我有一个错误 Array out of bounds in here

TrainRecord[] neighbors = findKNearestNeighbors(trainingSet, testingSet[t], K);

你能帮我解决这个问题吗?

4

1 回答 1

0

如果它在您的“测试记录”循环中抛出“数组索引越界”,这意味着您的索引t在某些时候采用的值大于您在该循环中访问的数组的大小。您可以检查此修改循环以打印这些值和/或检查 t 是否超出范围:

for (int t = (numOfTestingRecord * sumNumOfRecord) / K; t < ((numOfTestingRecord + 1) * sumNumOfRecord) / K; t++){
        System.out.println("Array size: "+testingSet.length);
        System.out.println("Current index: "+t);   
        if (t > testingSet.length) {
            System.out.println("If you see this message you are in trouble");    
        }    
        TrainRecord[] neighbors = findKNearestNeighbors(trainingSet, testingSet[t], K);
        int classLabel = classify(neighbors);
        testingSet[t].predictedLabel = classLabel; //assign the predicted label to TestRecord
    }

您可能需要更改t的初始化或结束循环的条件。

于 2020-08-24T10:49:24.757 回答