java - 我在学习 ArrayList 时被困在这一点上
问题描述
我正在学习 Java 中的 ArrayList。我正在制作一个猜词的程序。我从教程中复制并粘贴了一些代码。但我不知道如何使用它们。程序编译成功。但没有任何输出。这是代码
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class App {
public static void main(String[] args) throws Exception {
// Below 4 lines are mine. Trying to call methods.
String[] ospd = { "hi,bye" };
mustHaveAt('h', 0, loadWords(6, ospd));
mustNotHave('h', loadWords(6, ospd));
}
public static List<String> loadWords(int len, String[] ospd) {
List<String> words = new ArrayList<String>(1000);
for (String word : ospd) {
if (word.length() == len) {
words.add(word);
}
}
return words;
}
public static void mustHaveAt(char ch, int position, List<String> aList) {
for (int i = aList.size() - 1; i >= 0; i--) {
String word = aList.get(i);
if (position >= word.length() || word.charAt(position) != ch) {
aList.remove(i);
}
if (position < word.length() && word.charAt(position) == ch) {
System.out.println("Word " + word + " has character " + ch + " at position " + position);
}
}
}
public static void mustNotHave(char ch, List<String> aList) {
Iterator<String> itr = aList.iterator();
while (itr.hasNext()) {
String word = itr.next();
if (word.indexOf(ch) >= 0) {
itr.remove();
}
}
}
}
解决方案
如果您想检查方法是否成功(猜测单词),请自己添加输出。
你可以这样做:
public static void mustHaveAt(char ch, int position, List<String> aList) {
for (int i = aList.size() - 1; i >= 0; i--) {
String word = aList.get(i);
if (position >= word.length() || word.charAt(position) != ch) {
aList.remove(i);
}
if (position < word.length() && word.charAt(position) == ch) {
System.out.println("Word " + word + " has character " + ch + "at position " + position)
}
}
}
如果在单词的所需位置出现带有所需字母的单词,此代码将为您提供输出
推荐阅读
- java - 将多个嵌套列表压缩在一起
- python - 在不使用 Pandas 或 Numpy 的情况下按 CSV 的字段计算寄存器数量
- javascript - React 组件只渲染组件标签
- javascript - 实时自动更新和持久化折线图到当前日期
- mysql - 在查询“错误代码:2013”期间失去与 MySQL v8 服务器的连接。
- python - 使用 CSV 的第二列按升序排序?
- netty - Netty ctx.executor().scheduleAtFixedRate 任务在通道关闭时也可以工作
- android-layout - Android多屏指南
- java - 我如何发送带有 groovy 错误的电子邮件(com.sun.mail.smtp.SMTPSendFailedException: 530-5.5.1 Authentication Required。了解更多信息)
- azure-ad-b2c - 根据扩展属性阻止/拒绝用户登录