数据转换-16

在所有的系统之中,用户输入的数据永远是String表示,例如:如果用户输入年龄,则应该是字符串转为数字。(字符串变为指定的基本数据类型)
Integer类:public static int parseInt(String s)
Double类:public static int parseDouble(String s)
Boolean类:public static int parseBoolean(String s)

范例:字符串变为int型数据;
public class Wraaerclasse {
public static void main(String[] args) {
// TODO Auto-generated method stub
String str="110";
int num=Integer.parseInt(str);//将String变为int
System.out.println(num*2);
}
}
但一定要记住,在这种转换过程之中,字符串必须全部由数字组成,如果里面出现了任何非数字,则会出现“NumberFormatException”错误信息
范例:字符串变为double 型数据;
public class Wraaerclasse {
public static void main(String[] args) {
// TODO Auto-generated method stub
String str="111.111";
double num=Integer.parseDouble(str)//将String变为double;
System.out.println(num*2);
}
}
范例:字符串变为boolean型数据;
public class Wraaerclasse {
public static void main(String[] args) {
// TODO Auto-generated method stub
String str="false";
boolean num=Integer.parseBoolean(str)//将String变为double;
System.out.println(num);
}
}
在此类转换过程之中,如果字符串不是true或是false,那么统一为false.


如何将基本数据类型变为字符串?
方式一:
public class Wraaerclasse {
public static void main(String[] args) {
// TODO Auto-generated method stub
int num=100;
String str=num+" ";
System.out.println(str+","+str.length());
}
}
但是这种方式会产生垃圾,所以一般不使用。
方式二:在String类之中提供了一系列的valueOf()方法可以使用
public class Wraaerclassf {
public static void main(String[] args) {
// TODO Auto-generated method stub
int num=100;
String str=String.valueOf(num);
System.out.println(str+","+str.length());
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值