274、Java基础50 - 数字与字符串【字符串转换、数字方法】 2019.11.21

1、数字转字符串

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

package digit;
  
public class TestNumber {
  
    public static void main(String[] args) {
        int i = 5;
         
        //方法1
        String str = String.valueOf(i);  // 5 
         
        //方法2
        Integer it = i;
        String str2 = it.toString(); // 5
         
    }
}

2、字符串转数字

调用Integer的静态方法parseInt

package digit;
  
public class TestNumber {
  
    public static void main(String[] args) {
 
        String str = "999";
         
        int i= Integer.parseInt(str);
         
        System.out.println(i);
         
    }
}

3、练习:字符串转换

参考上述步骤
把浮点数 3.14 转换为 字符串 “3.14”
再把字符串 “3.14” 转换为 浮点数 3.14

如果字符串是 3.1a4,转换为浮点数会得到什么?

package charactor;

public class TestNumber {
    public static void main(String[] args) {
	   float f = 3.14f;

       String str = String.valueOf(f);
       System.out.println(str);

       String str1 = "3.1a4";
       float f1 = Float.parseFloat(str1);
       System.out.println(f1);

    }
}

// 异常截图
在这里插入图片描述

4、数字方法

java.lang.Math提供了一些常用的数学运算方法,并且都是以静态方法的形式存在

5、四舍五入, 随机数,开方,次方,π,自然常数

package digit;
  
public class TestNumber {
  
    public static void main(String[] args) {
        float f1 = 5.4f;
        float f2 = 5.5f;
        
        //5.4四舍五入即5
        System.out.println(Math.round(f1));
        
        //5.5四舍五入即6
        System.out.println(Math.round(f2));
         
        //得到一个0-1之间的随机浮点数(取不到1)
        System.out.println(Math.random());
         
        //得到一个0-10之间的随机整数 (取不到10)
        System.out.println((int)( Math.random()*10));
       
        //开方,结果:3.0
        System.out.println(Math.sqrt(9));
        
        //次方(2的4次方)结果:16.0
        System.out.println(Math.pow(2,4));
         
        //π ,结果:3.141592653589793
        System.out.println(Math.PI);
         
        //自然常数 ,结果:2.718281828459045
        System.out.println(Math.E);
    }
}

6、练习:质数

  • 统计找出一千万以内,一共有多少质数

质数概念: 只能被1和自己整除的数
举例:
5只能被 1和5整除,所以是质数
8可以被2整除,所以不是质数
在这里插入图片描述

package charactor;

public class Prime {

    public static boolean isPrime(int i){
        for(int j = 2; j <= Math.sqrt(i); j++){
            if ( i % j == 0){
                return false;
            }
        }
        return true;
    }

    public static void main(String args[]){

        int num = 1000 * 10000;
        int count = 0;
        for (int i = 2; i <= num; i ++){
            if (isPrime(i)){
                count ++;
            }
        }
        System.out.println("一共有" + count + "个质数");

    }
}

7、参考链接

[01] How2j - 数字与字符串系列教材 (二)- JAVA中把数字转换为字符串,字符串转换为数字
[02] How2j - 数字与字符串系列教材 (三)- JAVA MATH类常用方法

发布了309 篇原创文章 · 获赞 229 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/youyouwuxin1234/article/details/103168113