如何在java中使用indexOf检查数组中的数据

时间:2015-09-11 17:18:46

标签: java arrays indexof

我对java很新,我试图使用indexOf来检查一个人的名字是否以数组中的字母结尾并输出一个与之押韵的单词。我哪里错了?例如迪恩结束于" ean"所以它与绿色押韵。谢谢你们

    String [] first = new String [3];
    first [0] = "eem";
    first [1] = "een";
    first [2] = "ean";

    for (int i = 0; i < first.length; i++) {

        if (first[i].indexOf(first.length) != -1){
            System.out.println("That rhymes with green");
        }
    }

3 个答案:

答案 0 :(得分:2)

要检查天气,输入包含给定元素的任何数组,您应该收到input,然后遍历数组进行查看。对于前

  String personname = "Dean";
  String [] first = new String [3];
    first [0] = "eem";
    first [1] = "een";
    first [2] = "ean";

    for (int i = 0; i < personname.length; i++) {    
        if (input.indexOf(first[i]) != -1){  // check my input matched
            System.out.println("That rhymes with green");
        }
    }

答案 1 :(得分:0)

我已在测试器上测试并运行它。这工作正常。请评论任何问题。感谢

import java.util.*;

public class HelloWorld
{

    public static void main(String []args)
        {
            String [] first = new String [3];
            first [0] = "eem";
            first [1] = "een";
            first [2] = "ean";

            /* I am trying to get the input from user here */

            String s;
            Scanner in = new Scanner(System.in);
            System.out.println("Enter the string:");
            s = in.nextLine();

            /* Now, String.indexOf(substring) will check the condition if the match happens it will print the output, if it doesn't it returns -1 */

            for (int i = 0; i <s.length(); i++) 
                {    
                    if (s.indexOf(first[i]) != -1)
                        { 
                            System.out.println("That rhymes with green");
                        }
                }

       }
}

答案 2 :(得分:0)

您应该使用endsWith代替indexOfindexOf将返回传递的字符串与当前字符串完全匹配的索引,顾名思义,endsWith将检查当前字符串是否以传递的字符串结尾。

看看以下代码:

String personName = "Dean";
String[] suffix = {"eem", "een", "ean"};
String[] names = {"greem", "green", "grean"};

for(int i = 0; i < suffix.length; i++) {
    if (personName.endsWith(suffix[i])){
        System.out.println("That rhymes with " + names[i]);
    }
}

另外,理想情况下,您需要保留suffix -> name的地图以保持可维护性,但为了简单/探索,这应该没问题。