2016-05-03 40 views
0

我不知道如何在JAVA中将整数转换为24小时格式。如何在JAVA中将整数转换为24小时格式?

例如:

public class Activity 
{ 
    private Subject subject; 
    private int start; 
    private int duration; 
    private String room; 
    private int capacity; 
    private int enrolled; 


public Activity(Subject subject, int start, int duration, String room, int capacity) 
{ 
    this.subject = subject; 
    this.start = start; 
    this.duration = duration; 
    this.room = room; 
    this.capacity = capacity; 
} 

@Override 
public String toString() 
{ 
    return subject.getNumber() + " " + start + " " + duration + "hrs" + " " + enrolled + "/" + capacity; 
} 
} 

在toString()方法,我想为int varaible开始到格式转换HH:00。开始变量是从0-2的整数 - 18. 我尝试添加方法是这样的:

public String formatted(int n) 
{ 
    int H1 = n/10; 
    int H2 = n % 10; 
    return H1 + H2 + ":00"; 
} 

那么变量开始传递给该方法。但它不起作用。我不明白哪里出了问题。

我需要一些帮助,请! PS:结果应该看起来像“48024 18:00 1hrs 0/200”,除了启动变量,我得到了正确格式化的所有其他变量。

+0

如果你这是一个Java 8的问题,我建议你使用[TemporalAccessor](http://docs.oracle.com/javase/8/docs/api/java/time/temporal/TemporalAccessor.html )开始时间和[TemporalAmount](http://docs.oracle.com/javase/8/docs/api/java/time/temporal/TemporalAmount.html)。对于日期格式,您有[DateTimeFormatter](https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html)。 – dabadaba

+0

还有一个java'Duration'类。 – bvdb

+0

也可以'返回“”+ H1 + H2 +“:00”;' – bvdb

回答

5

您的方法失败了,因为你的代码就相当于:

return (H1 + H2) + ":00"; 

所以它总结每个数字之前追加字符串!

你可以在 “正确”(或实际破解)就这样做:

return H1 + (H2 + ":00"); 

甚至更​​好,使用String.format

public String formatted(int n) { 
    // print "n" with 2 digits and append ":00" 
    return String.format("%02d:00", n); 
} 
+0

为什么不呢? String.format(“%02d:00”,n); –

+0

@NicolasFilotto显然!更正:) –

+0

感谢您的帮助! –

0

你可以这样做:

public String formatted(int n) 
{ 
    String hours = ""; 
    if(n < 10) 
    { 
     hours = "0" + n; 
    } 
    else 
    { 
     hours = "" + n; 
    } 
    return hours + ":00"; 
} 
+0

请问为什么我写的方法是错误的?我不明白?它看起来对我是正确的。 –

+0

@AlexMa看看ControlAltDel的答案为什么你错了...... – brso05

+0

谢谢你的帮助! –

2

你需要转换成字符串在您添加或将只需添加数字

public String formatted(int n) 
    { 
     int H1 = n/10; 
     int H2 = n % 10; 
     return H1 + "" + H2 + ":00"; 
    } 
+0

哦......这就是为什么!非常感谢!! –

0

简单的解决方法:return "" + H1 + H2 + ":00";会做。

Java只是从左到右处理这一行。 所以如果它第一次遇到两个整数,它会加起来。

但是,如果您通过放入String(即使它为空)开始,则行为将被纠正。

还有其他更具可读性的替代方案以及:

return String.valueOf(H1) + H2 + ":00"; 

也有许多实用工具类,可以帮助您SimpleDateFormatDuration会感到很有趣。但在你的情况下,保持简单。 :)

相关问题