【问题标题】:String to int gives nullpointerexception字符串到 int 给出 nullpointerexception
【发布时间】:2011-07-09 09:13:56
【问题描述】:

当我运行此代码时,字符串到 int 的转换会打印出 NULL 吗?当我打印出字符串时,它给了我一个字符串编号,但是当我尝试将该字符串转换为 int 时,它显示为 null,这是为什么呢?

for(int j = 0; j < removetrack.size(); j++){
   String removetrackArray[] = removetrack.get(j).split(" ");
   String candidateBefore = "";
   int removetracklocation = Arrays.asList(removetrackArray).indexOf(past)-1;

   if(removetracklocation != 1) {
      String candidateBefore = "";
      System.out.println(removetrack.get(j)+" location =  "+ removetracklocation +" "+ 
         (past)+" candidate name "+dictionary.get(votedfor) );
      candidateBefore= Arrays.asList(removetrackArray).get(removetracklocation+1);
      System.out.println(" this is a string "+candidateBefore);
      System.out.println( Integer.getInteger(candidateBefore));                         
   }    
}

【问题讨论】:

    标签: java string int


    【解决方案1】:

    Integer.getInteger 不会将您的字符串转换为 int,int 返回系统属性的值(请参阅http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Integer.html#getInteger(java.lang.String))。你应该改用Integer.parseInt

    【讨论】:

      【解决方案2】:

      Javadoc 救援:

      确定整数值 具有指定的系统属性 名字。

      使用Integer.parseInt 将字符串转换为int,使用Integer.valueOf 将字符串转换为Integer。

      【讨论】:

      • 呸。 +1 打字比我快。 :)
      【解决方案3】:

      来自Integer.getInteger 的文档:

      确定具有指定名称的系统属性的整数值。 第一个参数被视为系统属性的名称。系统属性可通过 System.getProperty(java.lang.String) 方法访问。然后将此属性的字符串值解释为整数值,并返回表示该值的 Integer 对象。可能的数字格式的详细信息可以在 getProperty 的定义中找到。

      如果没有指定名称的属性,如果指定的名称为空或null,或者如果属性没有正确的数字格式,则返回null。

      换句话说,它解析整数。要解析整数,请使用Integer.parseInt(获取int)或Integer.valueOf(获取Integer)。

      但是,即使您的描述也有点奇怪 - 您在标题中声称它给了您一个 NullPointerException,但您又说它打印的是 null。它是哪一个?他们非常不同。我看不出你给我们的代码会如何在Integer.getInteger 处抛出NullPointerException

      或者,如果这是用户输入的值,您可能希望改用java.text.NumberFormat

      【讨论】:

        【解决方案4】:

        Integer.getInteger() 用于系统属性:

        Integer.getInteger("sun.arch.data.model"); 
        

        【讨论】:

        猜你喜欢
        • 2023-03-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-17
        • 1970-01-01
        • 2011-08-09
        相关资源
        最近更新 更多