String.format() / 字符串拼接格式化输出数据

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lxf512666/article/details/52745138

用String.format()方法格式化输出 或 拼接字符串实现


exa:
实现格式化时间,此方法有三个int型参数,
输出类似09:03:12的时间格式
中间需要判断输入的数字是否符合实际情况,
比如小时数就不能大于24,如果大于24就提示输入错误。

public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        int hour = 0, minute = 0, second = 0;
        // 字符串拼接方式实现格式化输出
        String hours = "", minutes = "", seconds = "";
        lable1: {
            while (true) {
                do {
                    System.out.println("输入“-1” 退出循环测试\n请输入小时数:");
                    hour = cin.nextInt();
                    if (hour == -1) {
                        break lable1;
                    }
                    if (hour < 0 || hour > 24) {
                        System.out.println("输入的小时数不在范围内!请重新输入!");
                    }
                } while (hour > 24 || hour < 0);

                if (hour >= 0 && hour < 10) {
                    hours = "0" + hour;
                } else {
                    hours = hour + "";
                }
                do {
                    System.out.println("请输入分钟数:");
                    minute = cin.nextInt();
                    if (minute < 0 || minute > 60) {
                        System.out.println("输入的分钟数不在范围内!请重新输入!");
                    }
                } while (minute > 60 || minute < 0);
                if (minute >= 0 && minute < 10) {
                    minutes = "0" + minute;
                } else {
                    minutes = minute + "";
                }
                do {
                    System.out.println("请输入秒数:");
                    second = cin.nextInt();
                    if (second < 0 || second > 60) {
                        System.out.println("输入的秒数不在范围内!请重新输入!");
                    }
                    if (second >= 0 && second < 10) {
                        seconds = "0" + second;
                    } else {
                        seconds = second + "";
                    }
                } while (second > 60 || second < 0);
                System.out.println("根据输入转换后的时间为: " + hours + ":" + minutes
                        + ":" + seconds + "\n");
System.out.println("----------------------------------");


    // 方式二 凋用String.format()方法进行格式化
                hours = String.format("%02d", hour);
                minutes = String.format("%02d", minute);
                seconds = String.format("%02d", second);
            System.out.println("根据输入转换后的时间为:" +                hours + ":" + minutes + ":"  + seconds);
            }
        }
    }
展开阅读全文

没有更多推荐了,返回首页