Java常见编程题

文章提供了三个Java程序示例,包括计算输入日期在当年的第几天,使用多线程模拟售票系统限制每秒售出一张票,以及遍历指定文件夹并打印所有文件名。这些示例涵盖了日期处理、线程同步和文件I/O等基础编程概念。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 根据输入的日期(年月日),输出这一年的第几天

题目描述:根据输入的日期,计算是这一年的第几天

解题思路:

step 1:判断输入日期的合法性,如果输入不合法返回-1;

step 2:根据输入的月份,计算从1月到(month - 1)月的天数,如果是二月的话,就要判断该年是否为闰年(闰年,day加29天,反之,day加28天);

step 3:根据步骤二计算出来的数值,最后加上输入的date,输出即可。

详细代码:

public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        while(sc.hasNext()){
            int year = sc.nextInt();
            int month=sc.nextInt();
            int date=sc.nextInt();
            int day=0;
            if(year<=0 || month>12 || month<=0 || date>31 || date<=0){
                System.out.println(-1);
                return;
            }
            for (int i = 1; i < month; i++) {
                if(i==1 || i==3 || i==5 || i==7 || i==8 || i==10 || i==12){
                    day+=31;
                }else if(i==4 || i==6 || i==9 || i==11){
                    day+=30;
                 //能被400整除,或者能被4整除但不能被100整除的都是闰年   
                }else if(i==2 && (year%400==0 || (year%4==0 && year%100!=0) )){
                    day+=29;
                }else{
                    day+=28;
                }
            }
            day+=date;
            System.out.println("总天数为:"+day);
        }
    }

2. 开启5个线程卖100张票,每隔一秒钟卖一张票

public class TicketSales {
    /*
        * 1、创建线程数量为5的线程池
        * 2、同时运行5个买票窗口
        * 3、总票数为100,每隔一秒钟卖一张票
     */
    static int tickets=100;
    static String str="";

    public static void main(String[] args) {
        ExecutorService service = Executors.newFixedThreadPool(5);
        service.execute(new Runnable() {
            public void run() {
                while(tickets>0){
                    synchronized (str){
                        if(tickets>0){
                            System.out.println(Thread.currentThread().getName()+"线程任务开始卖票,卖票1张,剩余"+(--tickets)+"张");
                            try {
                                Thread.sleep(1000);//休眠一秒
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        });
        service.shutdown();
    }
}

3. 遍历文件夹下的所有文件,并输出文件夹下所有的文件名

public class IO {
    public static void main(String[] args) {
        //遍历某文件夹下的文件输出文件名
        File file=new File("C:\\Users\\28486\\Desktop\\test\\");
        File[] files = file.listFiles();
        if(files.length>0){
            for (File f : files) {
                System.out.println(f.getName());
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值