Math与Scanner类的常用方法

1、Math

  • 随机数

    Math.random()

    // 随机数的使用
    public class testRandom {
        public static void main(String[] args) {
            // Math.random() [0,1)
            // Math.random() * 10 [0,10)
            // Math.random() * 10 + 1 [1,11)
            // (int)(Math.random() * 10) + 1 [1,10]
            int i = (int)(Math.random() * 10) + 1;
            System.out.println(i);
        }
    }
    
  • 幂运算

    System.out.println(Math.pow(2, 3));// 2^3 结果为 double
    
  • 开根号

    System.out.println(Math.sqrt(4));// 结果为 double
    

2、Scanner(扫描器)

  • 接收控制台输入

    Scanner scanner = new Scanner(System.in);
    System.out.println("一个字符串");
    String str1 = scanner.nextLine();// 获取输入的字符串
    System.out.println("一个字符串");
    String str2 = scanner.next();// 获取输入的字符串
    System.out.println("一个int数值");
    int n = scanner.nextInt();// 获取输入的int值
    System.out.println("一个float数值");
    float m = scanner.nextFloat();// 获取输入的float值
    // 其他略
    

    nextLine()与next()的区别,前者是遇到回车结束,后者则是碰到空格或者回车结束,所以nextLine()可以接收空格但是next()不行,并且nextLine()要在其他接收控制台输入方法之前

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值