开发者

How to test whether a char is NOT in a string? (java, junit)

As title says, im having trouble with my junit tests passing for checking if a character is not in a string and how to check if an empty string doesnt have a character. here is the method i have:

     public static boolean isThere(String s, char value){
  for(int x = 0; x <= s.length(); x++){
   if(s.charAt(x) == value){
    return true;
   } else if(s.length() == 0){
    return false;
   }
  }
  return false;

And here is the junit test:

    public void testIsThere()开发者_如何学Go {
  {
   String sVal  = "Jeff George";
   boolean hasA = StringMethods.isThere(sVal,'e');
   assertTrue(hasA);
   boolean hasE = StringMethods.isThere(sVal, 'o');
   assertTrue(hasE);
   boolean notIn = StringMethods.isThere(sVal,'b');
   assertTrue(notIn);
  }
  {
   String sVal  = "";
   boolean nothingIn = StringMethods.isThere(sVal,'a');
   assertFalse(nothingIn);
   boolean notIn = StringMethods.isThere(sVal,'b');
   assertFalse(notIn); 
  }
 }

Thank you very much, appreciated


Use String.indexOf() instead:

public static boolean contains(String s, char value){
    return s != null && s.indexOf(value) > -1;
}

String sVal = "Jeff George";
assertTrue(contains(sVal, 'e'));
sVal = null;
assertFalse(contains(sVal, 'e'));


Why are you doing this? Your function is already implemented as a method on String. Use String.indexOf instead:

s.indexOf('a') == -1

I think Carl Manaster was right in the comments about your specific problem - you need to use assertFalse not assertTrue here:

String sVal  = "Jeff George";
boolean notIn = StringMethods.isThere(sVal, 'b');
assertFalse(notIn); // not assertTrue

As an aside, notIn is a terrible name for that variable - it means exactly the opposite of what it says. Maybe that is why you got confused.


With Java 6 you can just do

final String s = "This is a test";
s.contains("x"); // False
s.contains("t"); // True


What problem are you encountering ?

Firstly,

  for(int x = 0; x <= s.length(); x++){

doesn't look right. x is going to run off the end of your string (use x < s.length() instead if you want to iterate through a string). But higher level functions are available for doing what you want (see the other answers here).


If String.indexOf(char) returns -1, hasA is false. Otherwise, it's true.


Or, try StringUtils.contains() from apache commons - that will handle the null String case for you as well.

http://commons.apache.org/lang/api/org/apache/commons/lang/StringUtils.html#contains%28java.lang.String,%20char%29

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜