java - 数组 : if (data[a]. 的增强循环包含 ("word")) 问题:类型不兼容

标签 java arrays loops types

作业是从字符串数组中打印出一个单词。我为此使用 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/

相关文章:

c - 将数组的大小扩展到越来越多的变量

loops - 如何使用现有的for循环在Liquid模板中进行n次循环

java - 为什么这种排序在 Solr 中不起作用?

php - 从多个表中获取数据的最佳方式

java - 在连续调用的代码中使用HttpURLConnection

java - java方法接受大约一百个输入的简单方法是什么?

ruby - 遍历 Ruby 数组最惯用的方法,满足任意条件时退出?

javascript - jQuery 选择多个按钮

java - 删除 Android 中的复制保护

java - 如果有人通过快速设置菜单关闭 NFC,如何通知应用程序?