使用java语言实现时,分,秒之间的相互转换:
public class Time {
private int hour;//时
private int minute;//分
private int second;//秒
public static void main(String[] args) {
Time t=new Time(0,80,61);
t.display();
}
//构造方法
public Time(){
}
public Time(int hour, int minute, int second) {
this.hour = hour;
this.minute = minute;
this.second = second;
}
//SetGet方法
public int getHour() {
return hour;
}
public void setHour(int hour) {
this.hour = hour;
}
public int getMinute() {
return minute;
}
public void setMinute(int minute) {
this.minute = minute;
}
public int getSecond() {
return second;
}
public void setSecond(int second) {
this.second = second;
}
/*输出时分秒*/
public void display(){
while(this.getSecond()>=60){
this.second-=60;
this.minute++;
if(this.getMinute()>=60){
this.minute-=60;
this.hour++;
}else if(this.getSecond()>=3600){
this.second-=3600;
this.hour++;
}
}
System.out.println(this.hour+"时"+this.minute+"分"+this.second+"秒");
}
/*加时*/
public void addhour(int time){
this.setHour(this.getHour()+time);
}
/*加分*/
public void addminute(int time){
while(this.minute+time>=60){
this.minute-=60;
this.hour++;
}
this.minute+=time;
}
/*加秒*/
public void addsecond(int time){
while(this.second+time>=60){
this.second-=60;
this.minute++;
if(this.second+time>=3600){
this.second-=3600;
this.hour++;
}else if(this.minute>=60){
this.minute-=60;
this.hour++;
}
}
this.second+=time;
}
/*减时*/
public void subhour(int time){
if(this.hour-time<0){
System.out.println("你输入的时间不对");
this.setHour(0);
}else{
this.hour-=time;
}
}
/*减分*/
public void subminute(int time){
if(this.minute-time<0){
System.out.println("你输入的时间不对");
this.setMinute(0);
this.setSecond(0);
}else{
this.minute-=time;
}
}
/*减秒*/
public void subsecond(int time){
if(this.second-time<0){
System.out.println("你输入的时间不对");
this.setSecond(0);
}else{
this.second-=time;
}
}
}
以上代码可以实现,时分秒的加减方法,在转换时也是比较严谨
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)