2015-09-26 34 views
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)); 


     } 

    } 

回答

1
yearsTF.setText(String.format("%d", (int)years)); 
daysTF.setText(String.format("%d", (int)days)); 
hoursTF.setText(String.format("%d", (int)hours)); 
minutesTF.setText(String.format("%d", (int)minutes)); 
secondsTF.setText(String.format("%d", (int)(seconds+0.5))); 

数字应舍入,如果你使用这种方法。在被设置为文本之前,双打被转换为整数(例如,4.98变成4,4.32变成4)。

我在秒中加了“+ 0.5”,因为我们希望它被四舍五入。所以,如果我们还剩下58.7秒时,会出现这种情况: 58.7 + 0.5 = 59.2 - >转换成59

这也适用于:

yearsTF.setText(String.format("%d", (int)years)); 
daysTF.setText(String.format("%d", (int)days)); 
hoursTF.setText(String.format("%d", (int)hours)); 
minutesTF.setText(String.format("%d", (int)minutes)); 
secondsTF.setText(String.format("%.0f", seconds)); 
+0

这对具有余数的作品。但是,当我对31,536,000秒= 1年进行测试时,它会生成 -数字为几天,几小时,几分钟和几秒。我很好奇。你认为我可以将我的双打格式化为UNNECESSARY吗?我一直在探索四舍五入模式和BigDecimal,但是,我没有丝毫的想法来实现它。我刚刚在这个学期开始了Java,我不认为我的教科书甚至涵盖了它。谢谢,您的意见肯定会让我朝正确的方向发展。 –

+0

嘿,我更新了我的答案。我认为这种方式更好。 – Georan

+0

你有没有进口顶级的课程?我得到一个本地方法错误。 –