作业是从字符串数组中打印出一个单词。我为此使用 foreach 循环和 contains() 方法。 当我使用传统的 for 循环时它可以工作。通过增强循环,我似乎很难弄清类型。 错误消息说不兼容的类型:java.lang.String无法转换为int
成功后
public static void main(String[] args) {
String[] food = {"appel seed", "apple red", "aple Red", "abelApel"};
for (int i = 0; i < food.length; i++) {
if (food[i].contains("apple"))
System.out.println(food[i]);
}}
//Next, I started to apply the enhanced loop
//food[a] is the use - an integer/String
public static void main(String[] args) {
String[] food = {"appel seed", "apple red", "aple Red", "abelApel"};
for (String a : food) {
System.out.print(a + " ");
if (food[a].contains("apple"))
System.out.println(food[a]);
}
}
它应该从数组中打印出与“apple”匹配的单词: 上诉种子 苹果红
最佳答案
for(字符串a:食物)...
如果您愿意,将使用 4 个不同的 a
变量启动循环。
因此将 if 子句更改为
if (a.contains("apple"))
System.out.println("heureka i found the word: " + a);
关于java - 数组 : if (data[a]. 的增强循环包含 ("word")) 问题:类型不兼容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57501626/