- public class Test2 {
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- //提示用户输入
- System.out.println("请输入你想要转换的秒数(必须为大于0的整数)");
- //定义一个字符读取缓冲流
- BufferedReader bufr=null;
- try{
- //读取键盘输入
- bufr=new BufferedReader(new InputStreamReader(System.in));
- String line=null;
- //定义要转换的秒数的变量
- int seconds=0;
- //如果用户输入的值不符合int整数,则循环读取直到符合规则
- while((line=bufr.readLine())!=null){
- try{
- //如果不能转为int,则抛出NumberFormatException异常
- seconds=Integer.parseInt(line);
- //catch异常
- }catch(Exception e){
- System.out.println("请按要求输入");
- //回到循环开始,重新等待用户输入
- continue;
- }break;
- //调用toDays方法获取要打印的字符串
- }System.out.println(toDays(seconds));
- }catch(IOException e){
- System.out.println(e.toString());
- //关闭流
- }finally{
- if(bufr!=null)
- try{
- bufr.close();
- }catch(IOException e){
- System.out.println(e.toString());
- }
- }
- //实现将秒数转换为×天×时×分×秒格式
- }public static String toDays(int seconds){
- //定义存储天,时,分,秒的int变量
- int day;
- int hour;
- int min;
- int second;
- //定义显示天,时,分,秒的字符串变量
- String daystr="";
- String hourstr="";
- String minstr="";
- String secondstr="";
- min=seconds/60;
- if(min>0){
- second=seconds%60;
- secondstr=second+"秒";
- hour=min/60;
- min=min%60;
- minstr=min+"分";
- if(hour>0){
- day=hour/24;
- hour=hour%24;
- hourstr=hour+"时";
- if(day>0){
- daystr=day+"天";
- }
- }
- }return daystr+hourstr+minstr+secondstr;
- }
- }
复制代码
我也想了蛮久的 |