好,所以我最近大约一个星期前开始用Java编程,我试图编写一个程序,该程序将花费毫秒,并给我几小时,几分钟,几秒钟和剩余的毫秒数。现在,由于某种原因,我将其中的大部分减少了,给了我一些数字。我应该得到2小时,46分钟,40秒和123毫秒。但是相反,我得到了2小时,2分钟,3秒和123毫秒。
在这里输入我的代码
int beginning = 10000123; //beginning is the starting number of milli seconds
int hours = beginning/3600000;
int rSecs = beginning%1000; //r = remaining
int minutes = rSecs/60;
int seconds = rSecs%60;
int milliSecs = rSecs%1000;
System.out.println("Lab03, 100 Point Version\n");
System.out.println("Starting Milliseconds" + beginning);
System.out.println("Hours:" + hours);
System.out.println("Minutes:" + minutes);
System.out.println("Seconds:" + seconds);
System.out.println("Milli Seconds:" + milliSecs);
感谢所有帮助!
答案 0 :(得分:1)
您需要用3600000
取模,以保持毫秒数
int hours = beginning/3600000;
int rMiliSecs = beginning%3600000;
由于毫秒,您需要将分钟除以60000(1m-> 60s-> 60000ms),然后除以60000以求余数
int minutes = rMiliSecs/60000;
rMiliSecs = rMiliSecs%60000;
然后将秒除以1000,然后以模数除以1000(1s-> 1000ms),以获取剩余的毫秒数
int seconds = rMiliSecs/1000;
int milliSecs = rMiliSecs%1000;
答案 1 :(得分:0)
如果您想避免使用魔幻数字,并采取更多面向对象的方法,则可以使用Duration类。
Duration duration = Duration.ofMillis(10000123);
long hours = duration.toHours();
duration = duration.minusHours(hours);
long minutes = duration.toMinutes();
duration = duration.minusMinutes(minutes);
long seconds = duration.getSeconds();
duration = duration.minusSeconds(seconds);
long milliSec = duration.toMillis();