String to int给出了nullpointerexception

时间:2011-07-09 09:13:57

标签: java string int

当我运行此代码时,字符串转换为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));                         
   }    
}

4 个答案:

答案 0 :(得分:8)

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

答案 1 :(得分:2)

Javadoc救援:

  

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

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

答案 2 :(得分:0)

来自Integer.getInteger的文档:

  

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

     

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

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

然而,即使你的描述有点奇怪 - 你在标题中声称它给你一个NullPointerException,但你说它正在打印null。这是什么?他们非常不同。我无法看到您提供给我们的代码如何在NullPointerException处抛出Integer.getInteger

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

答案 3 :(得分:0)

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

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