(Insertion Sort) Java error: Cannot find symbol

3323 views java
3

I'm trying to revise my code for Insertion Sort. First I have 2 arrays: one int array for ages, and a string array to store names corresponding to the ages. I tried to sort the ages array with ascending order and it worked fine. When I declare the string array for names and try reordering it so that the names are still corresponding to the sorted ages, the code won't compile and has 1 Cannot find symbol error:

symbol: variable names location: variable sort of type InsertionSort

But it doesn't report an error for variable sort.ages and runs normally if I delete this line: sort.names = new String[] {"a", "b", "c", "d", "e", "f", "g"};

import java.util.Arrays;
public class newInsertionSort {

int[] ages; //= {19, 20, 19, 80, 45, 5, 51};
String[] names;

void InsertionSort() {
    for (int i = 1; i < ages.length; i++) {
        int j = i;
        while (j>0 && ages[j] < ages[j - 1]) {
            int temp = ages[j];
            ages[j] = ages[j - 1];
            ages[j - 1] = temp;
            //add code to change the order of the names
            String temporary = names[j];
            names[j] = names [j-1];
            names [j-1] = temporary;
            j--;
        }
    }
    System.out.println(Arrays.toString(ages));
    System.out.println(Arrays.toString(names));
    }
}

class newInsertionSortTest {
public static void main (String[] args){
    InsertionSort sort = new InsertionSort();
    sort.ages = new int[] {19, 20, 19, 80, 45, 5, 51};
    //sort.names = new String[] {"a", "b", "c", "d", "e", "f", "g"}; this line causes the error
    sort.InsertionSort();
    }
}

answered question

It looks to me that you have two implementations sort of on top of each other. Maybe edit your code to just show the string sorting version.

You've got a method called InsertionSort, but you're trying to use it as if it's the name of a type here: InsertionSort sort = new InsertionSort();. That should be newInsertionSort sort = new newInsertionSort(); - although both your type and method names are unconventional.

Sorry, I'm a beginner so I don't quite get it. Do you mean the sort.ages and sort.names? Could you please elaborate? Thank you!

1 Answer

7

You have taken your class name as newInsertionSort , but you are creating object of InsertionSort in InsertionSort sort = new InsertionSort();

Just modify your object creation to-

NewInsertionSort sort = new NewInsertionSort();

It will work fine.

Also, in java class name starts with a capital letter.

posted this

Have an answer?

JD

Please login first before posting an answer.