包装类应用

包装类在实际中用的最多的还是字符串变为基本数据类型的操作,例如,将一个全由数字组成的字符串变为一个int或float类型的数据。在Integer和Float类中分别提供了一下两种方法:

1.Integer类(字符串转int型)

  public static int pareInt(String s)throws NumberFormatException

2.Float类(字符串转float型)

public static float pareseFloat(String s)throws NumberFormatException

但是在使用以上的两种操作时,一定要注意字符串必须由数字组成。

提示:方法声明throws说明

  在这两类操作语句中均存在throws语句,这表示的是异常处理语句,

范例:字符串变为基本数据类型

package test3;

public class WrapperDemo04 {
	public static void main(String[] args) {
		String str1 = "30";// 由数字组成的字符串
		String str2 = "30.3";
		int x = Integer.parseInt(str1);// 将字符串变为int型
		float f = Float.parseFloat(str2);// 将字符串变为float型
		System.out.println("整数乘方:" + x + "*" + x + "=" + (x * x));
		System.out.println("小数乘方:" + f + "*" + f + "=" + (f * f));
	}
}

  结果:

整数乘方:30*30=900
小数乘方:30.3*30.3=918.08997

posted on 2011-12-07 16:45  wangbokun  阅读(206)  评论(0编辑  收藏  举报

导航