将字符串转换为基本数据类型

将一个全由数字组成的字符串转换为int类型,可以采用Integer类的方法:public static int parseInt(String s) throws NumberFormatException。将一个全由数字组成的字符串转化为float类型,可以采用Float类的方法:public static float parseFloat(String s) throws NumberFormatException。

package com.test.ysg;

class StringParse {

	/**
	 * 将全由数字组成的字符串转换为int、float类型
	 */
	public static void main(String[] args) {
		String x = "3";
		String y = "4.5";
		int xx = Integer.parseInt(x);
		float yy = Float.parseFloat(y);
		//字符串x
		System.out.println("x + x = " + (x+x));
		//int类型xx
		System.out.println("xx + xx = "+ (xx+xx));
		//double类型yy
		System.out.println("yy + yy = " + (yy+yy));
	}

}
运行结果为:

x + x = 33

xx + xx = 6

yy + yy = 9.0

Integer和Float属于包装类。包装类就是将基本数据类型包装为一个类。包装类在实际中用得最多的还是字符串变为基本数据类型的操作。

包装类
序号基本数据类型包装类
1intInteger
2charCharacter
3shortShort
4longLong
5floatFloat
6doubleDouble
7booleanBoolean
8byteByte

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值