package time;
import java.util.Scanner;
public class StringTimeCount {
public static void main(String[] args) {
System.out.println("请输入原始数据:(数据应满足时间为 xx:xx ,而不应该包含xx:xx:xx,也就是包含几小时)");
System.out.println("最后一行输入0表示输入结束");
Scanner scanner = new Scanner(System.in);
String str = "";
while (true) {
String str_ = scanner.next();
if (str_.equals("0"))
break;
str += str_;
}
while (true) {
int index = str.indexOf(":"); //获取字符在字符串中第一次出现的索引
if (index == -1) {
return;
}
String str_ = str.substring(index - 2, index + 3);
// System.out.println(str_); //截取时间段的字符串
/*
我这边的截取只是为了配合我的TimeCountApp进行时间计算而略去了':'字符
*/
System.out.println(str.substring(index - 2, index)+""+str.substring(index+1 , index+3));
/*获取后就将它抹去,好在下次循环定位新的时间索引*/
str = str.replace(str_ , "");
}
}
}
这是字符串处理程序入口
这样将你想统计的信息全部复制到StringTimeCount程序的输入中,即可返回简单的时常列表
package time;
import java.util.Scanner;
/**
* 这个是完成时间相加的类
*/
public class Time {
//属性
int num;
int hour;
int minute;
int second;
public void TimeCountOOP() {
Scanner scanner = new Scanner(System.in);
System.out.println("======时间统计开始=======");
int[] timeNum = new int[10];
System.out.println("请输入你要统计的时间,如果是1:57,输入157即可,结束请输入0");
// for (int i = 0; i < timeNum.length; i++) {
// timeNum[i] = scanner.nextInt();
// if (timeNum[i] == 0) {
// break;
// }
// }
int i = 0;
boolean judge = true;
while (judge) {
if (i == timeNum.length) {
int[] newtimeNum = new int[timeNum.length+i]; //两倍动态扩容
for (int j = 0; j < timeNum.length; j++) {
newtimeNum[j] = timeNum[j];
}
timeNum = newtimeNum;
}
timeNum[i] = scanner.nextInt();
if(timeNum[i] == 0){
judge = false;
}
i++;
}
hour = classify(timeNum) / 6000;
minute = classify(timeNum) / 100;
second = classify(timeNum) % 100;
if (hour == 0) {
System.out.println("总计为:" + minute + "分" + second + "秒");
} else {
minute = minute % 60;
System.out.println("总计为:" + hour + "小时" + minute + "分" + second + "秒");
}
}
public int classify(int... nums) {
minute = 0;
second = 0;
for (int i = 0; i < nums.length; i++) {
minute += nums[i] / 100;
second += nums[i] % 100;
}
minute += second / 60;
second = second % 60;
return minute * 100 + second;
}
}
package time;
/**
* 直接调用Time对象
*/
public class TimeCountApp {
public static void main(String[] args) {
Time time = new Time();
time.TimeCountOOP();
}
}
在类TimeCountApp中运行,将StringTimeCount程序返回的时常输入进这个程序的输入里,即可返回总时长