我正在尝试修改我的插入排序代码。首先,我有2个数组:一个用于年龄的int数组,和一个用于存储与年龄相对应的名称的字符串数组。我试图按升序对ages数组进行排序,但效果很好。当我声明名称的字符串数组并尝试对其重新排序以使名称仍与排序的年龄相对应时,代码将无法编译,并且出现1找不到符号错误:
符号:变量名 location:类型为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();
}
}
答案 0 :(得分:1)
您已将类名命名为newInsertionSort,但是您正在InsertionSort中创建InsertionSort的对象sort = new InsertionSort();
只需将您的对象创建修改为-
NewInsertionSort sort = new NewInsertionSort();
它将正常工作。
此外,在Java类中,名称以大写字母开头。
答案 1 :(得分:1)
检查您的班级名称!它是'newInsertionSort';尝试使用以下代码重新编码:
newInsertionSort sort = newInsertionSort();
答案 2 :(得分:0)
您已声明InsertionSort sort = new InsertionSort();
这行。
此处您尚未定义InsertionSort
,但尝试使用它。因此,编译器说,我无法找到类型为sort
的名称为InsertionSort
的变量。
此外,即使您删除了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){
newInsertionSort sort = new newInsertionSort(); // Changed code here
sort.ages = new int[] {19, 20, 19, 80, 45, 5, 51};
sort.names = new String[] {"a", "b", "c", "d", "e", "f", "g"};
sort.InsertionSort();
}
}
这将起作用。
此外,作为附带说明,Java对所有声明都使用驼峰式。
class ClassName {}
void methodName() {}
int variableName = 0;
请尝试遵循这些规则,因此,当与更多开发人员合作时,您将不会遇到任何问题。