import java.util.Scanner;
public class Test4 {
public static void main(String[] args) {
int time = getTime();//调用getTime(),将result的值返回给time
outTime(time);
}
private static int getTime() {//获取输入时间
boolean flag = true;//定义标记flag
int result = 0;//初始化result的值
while (flag){//对输入的值进行判断
Scanner in = new Scanner(System.in);//声明扫描仪in
System.out.println("输入一个大于0的整数:");
try{//将输入的值转成整数值
result = Integer.parseInt(in.nextLine());
if (result < 0) {
throw new Exception("输入的值必须大于等于0");
}
flag = false;//如果result大于0,则终止循环
} catch(Exception e) {//捕获异常,并输入异常信息
System.out.println("输入值非法,请输入大于0的整数!");
}
}
return result;//循环结束,返回result的值
}
private static void outTime(int time){//对输入值进行算术运算
int s = 0, m = 0, h = 0, d = 0;
if (time < 0){return ;}//小于零终止判断,此处有点多余
if (time < 60) {
s = time;
} else if (time >= 60 && time < 60*60 ){
m = time/60;
s = time%60;
} else if (time >= 60*60 && time < 24*60*60){
h = time/(60*60);
m = time%(60*60)/60;
s = time%(60*60)%60;
} else {
d = time/(24*60*60);
h = time%(24*60*60)/(60*60);
m = time%(24*60*60)%(60*60)/60;
s = time%(24*60*60)%(60*60)%60;
}
format(d, h, m, s);//调用format()格式化时间
}
//格式化时间
private static void format(int d, int h, int m, int s) {
String str = "";
if (d != 0) {
str += d + "天";
}
if (h != 0) {
str += h + "小时";
}
if (m != 0) {
str += m + "分钟";
}
if (s != 0) {
str += s + "秒";
}
System.out.println(str);
}
} |