我收到一条错误消息"The method compare(String, String) is undefined for the type String"为什么我无法对 2D 数组进行排序?



我正在开发一个危险的 GUI 游戏,我在其中对我的 2d 问题数组进行排序。我在返回的 .compare 行上收到错误。错误显示"方法比较(字符串,字符串(未定义字符串类型"

JButton btnSort = new JButton("Sort");
btnSort.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String[][] questions = new String[][] { {"How many continents are there?"}, {"What is the capital of Canada?"}, {"What is the largest country in the world?"}, {"What is the largest ocean in the world?"}, {"How many oceans are there in the world?"}, {"How many countries make up Africa?"}, {"How many countries in the world begin with the word United?"}, {"Where is Milan?"}, {"What is the least populated US state?"}, {"What is the capital of Australia?"}, {"How many countries begin with the letter J?"}, {"Which country has the most lakes in the world?"}};

java.util.Arrays.sort(questions, new java.util.Comparator<String[]>() {
public int compare(String[] a, String[] b) {
return String.compare(a[0], b[0]);
}
});
}
});

因为String.compareTo(String)是一个采用两个参数的static方法(并且没有命名为compare(。它是一种实例方法,可以将一个String实例与另一个实例进行比较;喜欢

java.util.Arrays.sort(questions, new java.util.Comparator<String[]>() {
public int compare(String[] a, String[] b) {
return a[0].compareTo(b[0]);
}
});

这是因为您使用比较方法作为静态方法。像使用任何其他实例方法一样使用它。您甚至可以使用 compareTo((。

相关内容

最新更新