首页 > 解决方案 > (插入排序)Java 错误:找不到符号

问题描述

我正在尝试修改我的插入排序代码。首先,我有 2 个数组:一个用于年龄的 int 数组,一个用于存储与年龄相对应的名称的字符串数组。我尝试按升序对年龄数组进行排序,效果很好。当我为名称声明字符串数组并尝试对其重新排序以使名称仍与排序的年龄相对应时,代码将无法编译并出现 1 找不到符号错误:

符号:变量名称位置:类型为 InsertionSort 的变量排序

但是如果我删除此行,它不会报告变量 sort.ages 的错误并正常运行: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();
    }
}

标签: java

解决方案


检查你的班级名称!它是'newInsertionSort';尝试重新编码:

newInsertionSort sort = newInsertionSort();

推荐阅读