在新类中创建方法;在主类中找不到符号错误



我知道这可能是一个被问了一百万次的错误,但我真的很难理解为什么我的一个特定任务会出现这个问题。

我将创建一个方法类,它将遍历一个名为"list"的String[]单词,并按字母顺序对它们进行排序。我以为这会很容易。。

这就是我所拥有的,我对实际的排序没有问题,我只是无法让Java理解我正在尝试调用该方法。我得到了一个特定的类名、主类代码和方法头,所以我不能更改它,否则我就不能使用代码运行器。

class Lesson_15_Activity{
public static void sortAndPrint(String [] list){ //cant change
for (int pos = 0; pos < list.length-1; pos++){
for (int k = 0; k <= pos; k++){ //
if (list[k].compareTo(list[pos]) < 0){
list[pos] = list[k];
}
}
}
for (int a = 0; a < list.length-1; a++){
System.out.println(list[a]);
}
}
}
//the main method 
class Main {
public static void main(String[] args) {
String [] list = { "against" , "forms" , "belief" , "government" , "democratic" , "movement" , "understanding"};
sortAndPrint(list);
//^this is where i get the error
}
}

我在以前的课程中尝试过添加这样的代码,但无法实现。

private String[] words;
public setWords(){
words = list;
}

你可以像这个一样直接前进

import java.util.Arrays;

public class Lesson15Activity {
public static void main(String[] args) {
String[] list = {"against", "forms", "belief", "government", "democratic", "movement", "understanding"};
sortAndPrint(list);
//^this is where i get the error
}
public static void sortAndPrint(String[] list) { //cant change
Arrays.stream(list).sorted().forEach(e -> System.out.println(e));
}
}

您定义了两个类:Lesson_15_ActivityMain,并且尝试使用方法sortAndPrint,因为类Main是在Lesson_15_Activity中定义的。

一个简单的解决方案是加入两个类:

class Lesson_15_Activity{
public static void sortAndPrint(String [] list){ //cant change
for (int pos = 0; pos < list.length-1; pos++){
for (int k = 0; k <= pos; k++){ //
if (list[k].compareTo(list[pos]) < 0){
list[pos] = list[k];
}
}
}
for (int a = 0; a < list.length-1; a++){
System.out.println(list[a]);
}
}
public static void main(String[] args) {
String [] list = { "against" , "forms" , "belief" , "government" , "democratic" , "movement" , "understanding"};
sortAndPrint(list);
//^this is where i get the error
}
}

最新更新