JAVA程序练习DAY1

1.加法判断对错问题

目录

1.加法判断对错问题

2. 显示当前时间代码


import java.util.Scanner;  //引入Scanner类
public  class AdditionQuiz {
    public static void main (String[] args) {

            int number1 = (int) (System.currentTimeMillis() % 10); //生成随机数
            int number2 = (int) (System.currentTimeMillis() / 7 % 10); //生成第二个随机数


            Scanner input = new Scanner(System.in);
            System.out.print("What is " + number1 + " + " + number2 + " ? \n");

            int answer = input.nextInt();
            System.out.println(number1 + " + " + number2 + " = " + answer + " is " + (number1 + number2 == answer));

    }
}

这里牵扯到JAVA里面如何生成随机数问题,JAVA里面有三种生成随机数的方法

网上找到的使用方法:【三种方法】Java生成指定范围内随机数_java随机生成指定范围的数字-优快云博客

像我这里用的就是第三种方法(时间戳),由于可能是同一时间所以可能产生相同的随机数

其中的System.currentTimeMillis() % 10会返回一个long类型的数,使用int强制转换

也可以换成Math.random()返回一个双精度的0.0~1.0的随机数然后乘以10的n次方进行强制转换

例如:(int) Math.random()*10就能返回一个0~9的数

然后从外部输入使用的input是Scanner需引入)的一个方法

然后最后一行的代码里面的==是判断等号两边是否相等然后返回一个bool型的结果(T or F)

运行结果:

2. 显示当前时间代码

public class ShowCurrentTime {
    public static void main(String[] args) {

        long totalMilliseconds = System.currentTimeMillis(); //该函数返回从1970年1月1日到当前时间的毫秒数
        long totalSeconds = totalMilliseconds / 1000;
        long currentSecond = totalSeconds % 60;
        long totalMinutes = totalSeconds/60;
        long currentMinute = totalMinutes % 60;
        long totalHours = totalMinutes / 60;
        long currentHour = totalHours % 24;

        System.out.println("Current time is "+currentHour +" : "+currentMinute +" : "+currentSecond +" GMT");
    }
}

这个程序很有意思,能返回当前的格林威治时间(不是北京时间啊哈哈)

也说明了currentTimeMillis()这个方法的返回值的特点

运行结果:

今天有点事很仓促,下次多写点

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值