【概念理解】Java中parseXXX和valueOf,toString的区别

parseXXX()

parseXXX()是SimpleDateFomat里面的方法,有一个参数和两个参数的方法。一个参数时会按照对象数据类型不同分为parseInt(), parsefloat()和parsedouble(),将字符串参数变为数字(整数、浮点数)。两个参数时则是先将第一个参数变成整数,再以第二个参数指定的进制将这个整数变成十进制,即,若第二个参数为N,则先假定第一个参数是N进制数,再将次N进制数转化为十进制数。注意,返回值只能是整数。


public class test {
	public static void main(String args[]) {
		String op="123";
		int i=Integer.parseInt(op);
		float f=Float.parseFloat(op);
		double d=Double.parseDouble(op);
		
		System.out.println(i);//结果是123
		System.out.println(f);//结果是123.0
		System.out.println(d);//结果是123.0
	}
}

若字符串不能被转换成数字(字符串里有非数字的字符),则会报错(如op="123s")

Exception in thread "main" java.lang.NumberFormatException: For input string: "123s"
	at java.lang.NumberFormatException.forInputString(Unknown Source)
	at java.lang.Integer.parseInt(Unknown Source)
	at java.lang.Integer.parseInt(Unknown Source)

ValueOf()

ValueOf()方法也有三种数据类型对应的方法。Integer.valueOf(), Float.valueOf()、Double.valueOf()和String.valueOf()是把某一类型的值转化为Integer、Float、Double或String类型的。//op可以是int、float、double或String类型。

(注意:是Integer类型,而不是int类型,int类型是表示数字的简单类型,Integer类型是一个引用的复杂类型。我也不懂,所以具体可以参考:https://blog.csdn.net/teacher_lee_zzsxt/article/details/79230501)

public class test {
	public static void main(String args[]) {
		String op="123";

		int i=Integer.valueOf(op);
		float f=Float.valueOf(op);
		double d=Double.valueOf(op);
		String s=String.valueOf(op);
		
		System.out.println(i);//结果是123
		System.out.println(f);//结果是123.0
		System.out.println(d);//结果是123.0
		System.out.println(s);//结果是123
	}
}

若字符串不能被转换成数字(字符串里有非数字的字符),则会报错(如op="123s")

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
	i cannot be resolved to a variable
	f cannot be resolved to a variable
	d cannot be resolved to a variable
	i cannot be resolved to a variable
	f cannot be resolved to a variable
	d cannot be resolved to a variable

toString()

toString()的作用是将数字转换成字符串。

public class test {
	public static void main(String args[]) {
		String op="123";

		int i=Integer.valueOf(op);
		float f=Float.valueOf(op);
		double d=Double.valueOf(op);
		
		System.out.println(i);//结果是123
		System.out.println(f);//结果是123.0
		System.out.println(d);//结果是123.0
		
		String s;
		s=Integer.toString(i);//将Integer变成字符串
		System.out.println(s);//结果是123
		s=Float.toString(f);//将Float变成字符串
		System.out.println(s);//结果是123.0
		s=Double.toString(d);//将Double变成字符串
		System.out.println(s);//结果是123.0
	}
}

toString()的参数必须和对象是同一个类型,赋值的变量一定是字符串型,否则无法编译。

发布了14 篇原创文章 · 获赞 33 · 访问量 9367
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章