简体   繁体   中英

JSoup From String to Int

I worked with JSoup in android studio. In my code i have this:

Elements description = document.select("something");

if i do this -

String foo = description.text();

everything works fine.

But if i do this -

int y = Integer.parseInt(description.text());

Why does my app crash?

All my code:

public Void doInBackground(Void... params) {
        try {
            // Connect to the web site
            Document document = Jsoup
                    .connect("something")
                    .userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko")
                    .get();
            Elements description = document.select("something");

            String foo = description.text();
            int fuu = Integer.parseInt(foo);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

请尝试int foo = Integer.parse(description.ownText());

It is pretty much impossible to say what it is going on in your code without the Stack Trace and the original HTML or URL. However, I see one possibility for the crash, that is that the string does not contain a valid number. Since you state that the printout of the string actaully prints out "65" I can only assume that the string may be using strange uft8 unicode characters that look like or are numbers but can't be interpreted by Integer.parseInt(String).

For example, if your input string is "𝟼𝟻" it may look like "65" but it is unicode using U+1D7FC (MATHEMATICAL MONOSPACE DIGIT SIX) and U+1D7FB (MATHEMATICAL MONOSPACE DIGIT FIVE)

A list of such number characters in unicode can be found here

A work around ( suggested in the comment here ) may be to use the Normalizer class :

String numberStr = Normalizer.normalize(description.text(), Form.NFKC);
Integer.parseInt(numberStr);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM