JavaAPI 练习

mac2024-07-20  53

算出截止到现在,你已经出生了多少天。

*实现步骤

获取出生年月日。获取当前时间现在的时间减去出生的时间。 import java.util.Scanner; public class Test{ public static void main(String[] args){ Scanner sc =new Scanner(System.in); System.out.println("请输入你的生日 年/月/日") String str =sc.nextLine(); //这里的next要用nextLine只有enter键才表示结束,next()遇到空格或者enter表示程序结束。 DateFormat df = new SimpleDateFormat("yyyy/MM/dd"); // 将读取到的字符串格式化。 Date birth =df.parse(str); //将字符串类型转换位日期类型。 Date d =new Date(); //获取当前时间。 Date begin =birth.getTime(); //计算1970/1/1 00:00 :00到出生那天过了多少毫秒。 Date now =d.getTime(); System.out.println("今天是你来到这个世界的第"+((now-begin)/1000/60/60/24)+"天"); } }

求n的阶乘:用大整数乘法

import java.util.Scanner; public class Demo01{ public static void main(String[] args) throws ParseException{ Scanner sc =new Scanner(System.in); System.out.println("请输入要阶乘到多少"); int n = sc.nextInt(); BigInteger b =new BigInteger("1"); BigInteger result =new BigInteger("1"); for(int i=1;i<=n;i++){ result =result.multiply(b); b =b.add(new BigInteger("1")) } System.out.println(result); } }

获取任意一年的二月有多少天,用Calendar类的方法.

import java.util.Scanner; public class Demo02{ public static void main(String[] args){ Scanner sc =new Scanner(System.in); int year =sc.nextInt(); Calendar ca =Calendar.getInstance; //Calendar是抽象类,不能实例化,但是提供了一个方法,供创建对象。 ca.set(year,2,1); //将时间设置位每年的3月1号 ca.add(ca.DATE,-1); //三月一号减一天既得出2月有多少天。 System.out.println(ca.get(Calendar.DATE)); } }

校验qq号码.输入一个字符串,判断是否是合法的qq号码

要求: 1, 必须是5-15位数字 2, 0不能开头

public class Demo03{ public static boolean isLegal(num){ if(num.length()>=15||num.length()<=5){ // 判断是否是5-15位数。 return false; } if(!num.startWith("0")) // 判断是否由零开始。 return false; char[] ch = num.toCharArray(); //将字符串转换位字符数组。 for(Character c:ch){ if(!ch[i].isDigital){ return false; } } return true; } public static void main(String[] args){ String qqnum ="1111111333333"; //第一种,自己写一个判断方法 System.out.println(Demo03.isLegal(qqnum)); //第二种方法,正则表达式。 String regex ="[1-9][\\d]{4,14}"; System.out.println(qqnum.matches(regex)); } }
最新回复(0)