java - 我收到一条错误消息,提示“String 类型的方法 compare(String, String) 未定义”为什么我不能对二维数组进行排序?
问题描述
我正在开发一个危险的 GUI 游戏,我在其中对我的二维问题进行排序。我返回的 .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)
不是采用两个参数的方法(并且没有命名为compare)。它是一种实例方法,可以将一个实例与另一个实例进行比较;喜欢,static
String
java.util.Arrays.sort(questions, new java.util.Comparator<String[]>() {
public int compare(String[] a, String[] b) {
return a[0].compareTo(b[0]);
}
});
推荐阅读
- django - Django Heroku 没有名为“我的应用程序名称”的模块
- c++ - 为什么这个浮点比较会产生错误?
- python - python - 不支持的操作数类型
- c# - 使用 Visual Studio 2015 发送调整图片大小的电子邮件
- c++ - 使用 cmake 包含静态库
- angular - 如何在 Docker 映像创建过程中从 npm-install 过程中排除 @angular/cli?
- sql-server - 如何从 SQL Server 中检索已排序的分层数据
- java - 在 Eclipse Oxygen 上运行 GWT
- c# - 线程 0xc28 已退出,代码为 0
- node.js - express 验证器 useFirstErrorOnly 不起作用