0

我知道这可能是一个错误被问了大约一百万次,但我真的很难理解为什么我会在我的一项特定任务中得到这个。

我将创建一个方法类,该类将遍历名为“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;
}
4

2 回答 2

0

你可以这样直奔

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));
    }
}
于 2020-04-27T20:07:22.657 回答
0

您定义了两个类:Lesson_15_ActivityMain,并且您尝试使用sortAndPrint自 class 以来的方法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
      }
}
于 2020-04-27T20:10:02.877 回答