简体   繁体   English

我想将 String 转换为 long

[英]I want convert String to long

I have String like this ""3333"" I want convert to Long but when convert I am seeing this Exception我有这样的字符串""3333""我想转换为Long但是在转换时我看到了这个异常

java.lang.NumberFormatException

I try many ways but I cant convert我尝试了很多方法,但我无法转换

I am trying this way我正在尝试这种方式

public void addNewFriend(List<String> mobileList, String login) {
    try {
        List<Long> list = new ArrayList<>();
        mobileList.forEach(x -> {
            log.debug(x);
            x=x.replace("\\\"","");
            Long y = Long.parseLong(x);
            log.debug(y.toString());
            list.add(y);
        });
        log.debug(list.toString());
        Set<AppUser> appUsers = appUserRepository.findByMobileNumberIn(list);
        if (appUsers.size() > 0) {
            AppUser appUser = appUserRepository.findByLogin(login);
            appUser.friends(appUsers);
            appUserRepository.save(appUser);
        } else {
            throw new BadRequestAlertException("cannot find user relation with author", "AppUser", "List is Empty");
        }
    } catch (NoSuchElementException e) {
        throw new BadRequestAlertException("Cannot find User", "Url", "Check your input");

    } catch (NullPointerException e) {
        throw new BadRequestAlertException("cannot find user relation with author", "AppUser", "List is Empty");

    } catch (Exception e) {
        throw new BadRequestAlertException(e.getMessage(), "Server Error", "Check it!");
    }


}

note: I am take this request from kafka I can't get mobile list in long direct注意:我收到来自 kafka 的这个请求,我无法直接获取移动列表

Remove the extra \\ because \\\" will look for \" which is not the case with your string.删除额外的\\因为\\\"会寻找\"这不是你的字符串的情况。

public class Main {
    public static void main(String[] args) {
        System.out.println(Long.parseLong("\"3333\"".replace("\"", "")));
    }
}

Output: Output:

3333

Just soultion change replace to replaceAll like this就像这样将替换替换为替换所有

    List<Long> list = new ArrayList<>();
mobileList.forEach(x -> {
    log.debug(x);
    x=x.replaceAll("\\\"","");
    Long y = Long.parseLong(x);
    log.debug(y.toString());
    list.add(y);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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