Long.parseLong 给出 java.lang.NumberFormatException

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27597841/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 12:05:27  来源:igfitidea点击:

Long.parseLong gives java.lang.NumberFormatException

java

提问by geekchic

So I've tried a whole bunch of things, but I'm unable to get around this. idin my Serviceclass is of data type long. I've tried to convert serviceAuthto long but it throws a java.lang.NumberFormatException. How do I fix this?

所以我尝试了很多东西,但我无法解决这个问题。id在我的Service班级是数据类型long。我试图转换serviceAuth为 long 但它会抛出一个java.lang.NumberFormatException. 我该如何解决?

String[] serviceList = getUser.serviceList.split(",");

for(String serviceAuth: serviceList) {
    Long temp = Long.parseLong(serviceAuth.toString());
    Criteria ctr = sessionFactory.getCurrentSession().createCriteria(Service.class)
                        .add(Restrictions.eq("id",temp));
}

serviceListlooks like this 5,18,19. It is loaded from a csv file.

serviceList看起来像这样5,18,19。它是从 csv 文件加载的。

When I print the values in the for loop, it looks like this:

当我在 for 循环中打印值时,它看起来像这样:

1
2
14
15

Error report:

错误报告:

 java.lang.NumberFormatException: For input string: ""
    java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    java.lang.Long.parseLong(Long.java:601)
    java.lang.Long.parseLong(Long.java:631)
    org.x.y.gateway.MainController.getUsers(MainController.java:1433)
    org.x.y.gateway.MainController$$FastClassBySpringCGLIB$e5db2d9.invoke(<generated>)
    org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
    org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:717)
    org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    org.springframework.transaction.interceptor.TransactionInterceptor.proceedWithInvocation(TransactionInterceptor.java:98)
    org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:266)
    org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
    org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:653)
    org.x.y.gateway.MainController$$EnhancerBySpringCGLIB$9bedb6.getUsers(<generated>)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:483)
    org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
    org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
    org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:781)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:721)
    org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    org.x.y.gateway.CrossOriginRequest.doFilter(CrossOriginRequest.java:18)

回答by kriegaex

Your problem is that one of the strings created by split()is empty or contains whitespace, e.g.

您的问题是由创建的字符串之一split()为空或包含空格,例如

package de.scrum_master.app;

public class Application {
    public static void main(String[] args) {
        String[] serviceList = ",15,18,19".split(",");
        for (String serviceAuth : serviceList) {
            Long temp = Long.parseLong(serviceAuth.toString());
            System.out.println(temp);
        }
    }
}
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Long.parseLong(Unknown Source)
    at java.lang.Long.parseLong(Unknown Source)
    at de.scrum_master.app.Application.main(Application.java:7)


Update: How to fix the problem

更新:如何解决问题

You should do two things:

你应该做两件事:

  • Make the split regex more stable against leading and trailing spaces.
  • Skip values of ""in the loop which can still occur at the beginning of the array.
  • 使拆分正则表达式对前导和尾随空格更稳定。
  • 跳过""循环中仍可能出现在数组开头的值。
package de.scrum_master.app;

public class Application {
    public static void main(String[] args) {
        String[] serviceList = " , 15 , 18 , 19, ".split("[\s,]+");
        for (String serviceAuth : serviceList) {
            if ("".equals(serviceAuth))
                continue;
            Long temp = Long.parseLong(serviceAuth.toString());
            System.out.println(temp);
        }
    }
}
15
18
19

回答by Henry

The string you are trying to parse is not a correct long. The exception also shows you which string caused the problem.

您尝试解析的字符串长度不正确。该异常还向您显示是哪个字符串导致了问题。

回答by helsont

Something is wrong with your input data. "" means the string is empty. Long cannot parse an empty string.

您的输入数据有问题。"" 表示字符串为空。Long 无法解析空字符串。

回答by shikjohari

The String is empty (input string: ""), Try to hardcode it and print the result or provide the inputs here

字符串为空(输入字符串:“”),尝试对其进行硬编码并打印结果或在此处提供输入