作业是从字符串数组中打印出一个单词。我为此使用了 for each 循环和 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”的单词:appel seed apple red
for (String a : food) ...
a
如果您愿意,将开始一个包含 4 个不同变量的循环。
因此将您的 if 子句更改为
if (a.contains("apple"))
System.out.println("heureka i found the word: " + a);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句