Why won't the java String “contains” method re

2019-07-21 21:27发布

问题:

Here is the input to my function

"<div class=\"xbox\">TESTING<span class=\"newbox\"><a href=\"javascript:void(0);\" id=\"btnbox\">Use a new box</a></span></div><div class=\"cardnumber\">***-1111</div></div>"

When I do the below it never returns anything but -1

input.indexOf("cardnumber")

Any reason this isn't working? when I do an indexOf("div") it returns fine ... (help)

thanks guys (sorry for not posting the unit test earlier)

public Cart viewCart() {
        ResponseAndCookies result = service.makeHttpRequestWithUrl("https://www.xbox.com/account/fakebox/");
        String response = result.getResponse();

        String availableCreditCard = "<div class=\"cardnumber\">***";
        if (response.contains(availableCreditCard)) {
            return parseJson.parseCartAndReturnObject(response);
        }

        return null;
    }

    public class XboxViewCartServiceTest {
    @Test
    public void verify_cart_works_with_valid_login() {
        FakeXboxCartParseJson jsonParser = new FakeXboxCartParseJson();
        XboxViewCartService sut = new XboxViewCartService(new FakeXboxViewCartHttpBase(), jsonParser);
        Cart cart = sut.viewCart(null);

        Assert.assertTrue(jsonParser.calledMethod);
    }

    class FakeXboxViewCartHttpBase extends XboxHttpService {
        @Override
        public ResponseAndCookies doHttpPostWithUrl(String url, ResponseAndCookies responseAndCookies, String json) {
            ResponseAndCookies result = new ResponseAndCookies();
            result.setResponse("<div class=\"xbox\">TESTING<span class=\"newbox\"><a href=\"javascript:void(0);\" id=\"btnbox\">Use a new box</a></span></div><div class=\"cardnumber\">***-1111</div></div>");

            return result;
        }
    }

    class FakeXboxCartParseJson extends XboxCartParseJson {
        public boolean calledMethod = false;
        @Override
        public Cart parseCartAndReturnObject(String html) {
            calledMethod = true;
            return null;
        }
    }
}

回答1:

This obviously works as you provide it, so there are only 3 options:

  1. There are some non-printable characters in the string;
  2. There is an encoding issue when you read the input and compare;
  3. There's something wrong somewhere else that we cannot see because you don't give enough code.

For the moment, the best best is item 3.

Please provide more code.

EDIT (2011-05-23 02:20):

Thanks for the update to your question. So, now we still cannot be sure as we're missing the data returned by your endpoint, but there's a good chance if just doesn't exactly contain <div class="cardnumber">***.

Do make sure as well that you specify the right headers for your request and that you use valid content type and character encoding. Please make also sure that you are not using a strange encoding on your source files, as you might be inputting non-standard * characters without knowing it.