当前位置: 代码迷 >> Eclipse >> 线程 [main](已暂挂(错误 NullPointerException))如何解决
  详细解决方案

线程 [main](已暂挂(错误 NullPointerException))如何解决

热度:646   发布时间:2016-04-23 15:13:13.0
线程 [main](已暂挂(异常 NullPointerException))怎么解决?
package   socket;

public   class   Count4   {

public   static   int   counter;
static{
counter=(Integer.getInteger( "myApp.Count.counter ").intValue());//出错
}
}


package   socket;


public   class   TestStaticInit{
public   static   void   main(String[]   args){
System.out.println( "counter   =   "+   Count4.counter);//出错
}
}

------解决方案--------------------
counter=(Integer.getInteger( "myApp.Count.counter ").intValue());//出错
============
Integer.getInteger( "myApp.Count.counter ")

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

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

这样你上面那个错就很明显了。
myApp.Count.counter 是个什么东西?你定义在什么地方?

System.out.println( "counter = "+ Count4.counter);//出错
是由于上面那个错误引起的,不属于讨论范围。
------解决方案--------------------
Java doc:
getInteger
public static Integer getInteger(String nm)
Determines the integer value of the system property with the specified name.
The first argument is treated as the name of a system property. System properties are accessible through the System.getProperty(java.lang.String) method. The string value of this property is then interpreted as an integer value and an Integer object representing this value is returned. Details of possible numeric formats can be found with the definition of getProperty.

If there is no property with the specified name, if the specified name is empty or null, or if the property does not have the correct numeric format, then null is returned.

In other words, this method returns an Integer object equal to the value of:

getInteger(nm, null)

Parameters:
nm - property name.
Returns:
the Integer value of the property.
See Also:
System.getProperty(java.lang.String), System.getProperty(java.lang.String, java.lang.String)
------解决方案--------------------
中文的来了,既然是初学, 就不要整这么复杂的

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

第二个参数是默认值。如果未具有指定名称的属性,或者属性的数字格式不正确,或者指定名称为空或 null,则返回一个表示第二个参数的值的 Integer 对象。

换句话说,该方法返回一个等于以下值的 Integer 对象:

getInteger(nm, new Integer(val))
但在实践中可能会用以下类似方式实现它:
Integer result = getInteger(nm, null);
return (result == null) ? new Integer(val) : result;
从而避免在无需默认值时分配不必要的 Integer 对象。

参数:
nm - 属性名。
val - 默认值。
返回:
属性的 Integer 值。
另请参见:
System.getProperty(java.lang.String), System.getProperty(java.lang.String, java.lang.String)
  相关解决方案