JAVA --数字与字符串(二)字符串转换

数字转字符串

方法1: 使用String类的静态方法valueOf
方法2: 先把基本类型装箱为对象,然后调用对象的toString

String.vlaueof(变量名)

Integer对象.toString()

public class TestNumber {
    
    
	public static String getType(Object o) {
    
    
		return o.getClass().toString();
	}
	public static void main(String args[]) {
    
    
		int i =5;
		System.out.println(getType(i));
		
		
		String a = String.valueOf(i);//方法一
		System.out.println(getType(a));

		Integer it = i;
		String name = it.toString();//方法二
		System.out.println(getType(name));
	}
}

字符串转数字

Integer.parseInt(变量名)方法

public class TestNumber {
    
    
	public static String getType(Object o) {
    
    
		return o.getClass().toString();
	}
	public static void main(String args[]) {
    
    
		String a = "500";
		
		int b = Integer.parseInt(a);
		System.out.println(getType(b));
		System.out.println(b);
	}
}

练习-字符串转换

public class TestNumber {
    
    
	public static String getType(Object o) {
    
    
		return o.getClass().toString();
	}
	public static void main(String args[]) {
    
    
		float a = 3.14f;
		
		String b = String.valueOf(a);
		System.out.println(getType(b));
		
		float a1 = Float.valueOf(b);
		System.out.println(getType(a1));
	}
}

万能转换:

int a = 1;
String a1 = String.valueOf(a);

String a = "100";
int a1 = Integer.valueOf(a);

float a = 3.14;
String a1 = String.valueOf(a);

String a = "3.14";
float a1 = Float.valueOf(a);

猜你喜欢

转载自blog.csdn.net/qq_17802895/article/details/108712885