2017-09-13 67 views
-1

所以我必須用一個累加循環基本上看是否userInputted字符串中的字符出現在選定的字符串中。

下面我有我的代碼,下面是我用作它的測試用例。

public static boolean containsAll (String source, String target) 
{ 
    boolean contains = false; 
    scn = new Scanner (source); 


      String token = scn.next(); 


      if(target.contains(token) || token.isEmpty()) { 
       contains = true; 
      } 



     return contains; 
} 

這是測試用例。第一個不起作用,但其餘工作正常。

@Test 
public void testContainsAll() 
{ 
    assertTrue(containsAll("", "")); 
    assertTrue(containsAll("abc", "abracadabra")); 
    assertFalse(containsAll("def", "Defect")); 
    assertFalse(containsAll("x", "")); 
} 

在此先感謝。

+0

「報告中源的每個字符是否在目標至少發生一次」是不是什麼'不管contains'方法做,因爲它會檢查是否字符串包含指定子,而不是是否包含從字符串中的所有字符他們的訂單或金額。您需要遍歷字符串字符並檢查其他字符串中的某個字符是否與它相等。 – Pshemo

+2

''scn.next()''給你下一個單詞,而不是下一個字符... – f1sh

+0

好的一秒鐘大聲笑。我試圖想要做到這一點。 – SassyRegards201

回答

1

非常感謝所有幫助。我的代碼創建一個布爾變量並將其初始化爲true。然後我創建一個for循環遍歷userInputted字符串的所有字符,並且如果target在該迭代中不包含該字符的值,則contains將設置爲false。否則我返回包含之前已初始化爲true的內容。

public static boolean containsAll (String source, String target) 
{ 

    boolean contains = true; 

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

     if (!target.contains(String.valueOf(source.charAt(i)))) 
     { 
      contains = false; 
     } 
    } 

    return contains; 

} 
相關問題