Question:
Need help with toString method?
i messed up
2010-01-26 07:47:28 UTC
this is my program so far:

public class clock {

private int hour;
private int minute;
private int second;

//instance variables for the alarm

private int Ahour;
private int Aminute;
private int Asecond;


public clock(){
hour = 0;
minute = 0;
second = 0;
}

public clock (int h, int m, int s){
hour =h;
minute = m;
second = s;

}

public void setAlarm (int h, int m, int s){

Ahour = h;
Aminute = m;
Asecond = s;

}

public void alarmNoise (){
System.out.println("WAKe up") ;
}

public void reset () {
hour = 0;
second = 0;
minute = 0;
}

//public String toString() {
//String str =("%02d:%02d:02d", hour, minute, second);
//}***get help with this part


public void advance(){

if(hour==Ahour){
if(minute==Aminute)
if(second==Asecond)


alarmNoise();
}

if(second>=0){
second++;
if(second==60)
second = 0;
minute++;
if(minute==60)
minute = 0;
hour++;
if(hour==24)
hour = 0;
}
}
}


I need help finishing my toString method. It should put the current time in the form "hh:mm:ss"
Any advice would be greatly appreciated.
Four answers:
Digitalhigh
2010-01-26 08:05:10 UTC
Let me start with a disclaimer...I haven't programmed in several years, so I'm just going off of memory and what google is telling me...I apologize if my syntax is off. This is just a rough guide of what you *should* have to do.





Okay, try this:



String seperator; // - Define the variable you want to keep the seperator in

String seperator = ":"; // - Tell it to save the colon in that seperator value

string time += Integer.Tostring(hour); // - Adds the hour to the string

String time += seperator; // Adds the seperator

String time += Integer.Tostring(minute); // Adds the minute

String time += seperator; // Another seperator

String time += Integer.Tostring(second); // Tacks the ol' second on there.
?
2010-01-26 08:22:06 UTC
public String toString() {



return String.format("%02d:%02d:%02d", hour, minute, second);



}
Chris C
2010-01-26 08:08:53 UTC
public String toString() {

String str;

str.Format("%02d:%02d:02d", hour, minute, second);

return str;

}
Ben
2010-01-26 07:57:15 UTC
Look up the String.format method. I haven't used it, but I believe it works by using %2tf or something like that.



return String.format("%2f",4);



expended for everything else


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...