黑马程序员技术交流社区
标题:
编程详解
[打印本页]
作者:
透过生活
时间:
2014-1-21 15:15
标题:
编程详解
本帖最后由 透过生活 于 2014-2-16 18:47 编辑
从键盘接受一个数字,打印该数字表示的时间,最大单位到天
例如:
键盘输入6,打印6秒
键盘输入60,打印1分
键盘输入66,打印1分6秒
键盘输入666,打印11分6秒
键盘输入3601,打印1小时1秒
键盘输入86440,打印1天40秒
作者:
↑↓ME→←
时间:
2014-1-21 15:19
这是考试的题
作者:
奋斗的小雨
时间:
2014-1-21 16:14
我的基础测试里貌似也有这道题,不过我还没学到这额,慢慢来吧
作者:
宋星
时间:
2014-1-21 16:23
package com.itheima;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test1 {
public static void main(String[] args) {
BufferedReader bufr=new BufferedReader(new InputStreamReader(System.in));
String line=null;
System.out.println("请输入数字:");
try {
while((line=bufr.readLine())!=null)
{
if(line.equals("over"))
break;
int input;
try { //这个try...catch为处理键盘录入的字符是非数字的异常
//将字符串中的数字转换为int类型
input = Integer.parseInt(line);
number2time(input);
} catch (Exception e) {
System.out.println("输入的不是数字,请重新输入");
}
}
bufr.close();
} catch (IOException e) {
System.out.println("读取失败");
}
}
//将数字转换为时间的方法
public static void number2time(int input){
int days=0;
int hours=0;
int minutes=0;
int seconds=0;
//定义一个StringBuilder,装输出数据
StringBuilder time=new StringBuilder();
if(input<0){
//提醒数字不能小于零
System.out.println("数字不能小于零,请重新输入");
}
else if(input>=60){
minutes=input/60;
seconds=input%60;
if(minutes>=60)
{
hours=minutes/60;
minutes=minutes%60;
if(hours>=24){
days=hours/24;
hours=hours%24;
}
}
}
else {
seconds=input; //当传入的整数在0~60之间时,就只有秒数
}
if(days!=0){
time.append(days+"天");
}
if(hours!=0){
time.append(hours+"时");
}
if(minutes!=0){
time.append(minutes+"分");
}
if(seconds!=0){
time.append(seconds+"秒");
}
System.out.println(time);
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2