2015-09-11 31 views
0

我是相當新的Java和我試圖用indexOf來檢查一個人的名字是否以數組中的字母結尾並輸出一個字它押韻用。我哪裏錯了?例如院長以「ean」結尾,所以它用綠色押韻。謝謝你們我如何檢查數組中的數據與indexOf在java

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"); 
     } 
    } 
+0

看到我的代碼,讓我知道如果我失去了一些東西。直接在我的機器上運行它,它爲我工作。 – Jordon

回答

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可維護性,但是爲了簡單/探索這應該是罰款。

+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"); 
     } 
    } 
+0

只是爲了搭載這個。 OP代碼破壞的原因是因爲你正在測試陣列長度的第一個數組的內容。 'first [i] .indexOf(...)'將通過「eem」,「een」和「ean」循環,並檢查是否有等於長度的字符。所以你要檢查你的代碼是否「eem」有3個,而不是輸入是否有「eem」。 – Braains

+0

這個問題的部分是如何解決的,OP想知道輸入是否與其他數組中的一些押韻結尾。 –

+0

@FabianBarney是對的。列出的代碼會說「Deanery」與「綠色」押韻。 OP應該使用endsWith()而不是indexOf()。 – FredK

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"); 
         } 
       } 

     } 
}