1
我想盡可能準確地用Java編寫這個計算器。它需要幾秒鐘時間並將其轉換爲幾年,然後再細分日期,小時,分鐘和秒鐘。我已經格式化了我的答案,這樣我的textFields只顯示整個數字。不幸的是,當我使用%來拉動餘數來轉換其餘的變量時,如果我的十分位數是5或更多,它會將我的答案向上舍入。這是一個GUI,這裏是代碼。我猜這是一個寬容問題。使用yearsTF.setText(String.format(「%。0f」,years))時防止我的雙打四捨五入。
private class CalculateButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
double inputSeconds, years, days, hours, minutes, seconds;
inputSeconds = Double.parseDouble(inputSecondsTF.getText());
years = inputSeconds/60/60/24/365;
days = years % 1 * 365;
hours = days % 1 * 24;
minutes = hours % 1 * 60;
seconds = minutes % 1 * 60;
yearsTF.setText(String.format("%.0f", years));
daysTF.setText(String.format("%.0f", days));
hoursTF.setText(String.format("%.0f", hours));
minutesTF.setText(String.format("%.0f", minutes));
secondsTF.setText(String.format("%.0f", seconds));
}
}
這對具有餘數的作品。但是,當我對31,536,000秒= 1年進行測試時,它會生成 -數字爲幾天,幾小時,幾分鐘和幾秒。我很好奇。你認爲我可以將我的雙打格式化爲UNNECESSARY嗎?我一直在探索四捨五入模式和BigDecimal,但是,我沒有絲毫的想法來實現它。我剛剛在這個學期開始了Java,我不認爲我的教科書甚至涵蓋了它。謝謝,您的意見肯定會讓我朝正確的方向發展。 –
嘿,我更新了我的答案。我認爲這種方式更好。 – Georan
你有沒有進口頂級的課程?我得到一個本地方法錯誤。 –