I am a novice in this java and I just started classes, they have sent us this exercise:
Exercise 3
Design a called class
Reloj
with the integer attributes:hora
(24 hours),minuto
andsegundo
, and the following methods:A constructor that initializes attributes to values passed as parameters.
A method called Increment that increments the time by one second.
For example:
17:53:59
will be17:54:00
17:59:59
will be18:00:00
4.A method called Decrement that decreases the time by one second.
For example:
17:53:00
will be17:52:59
17:00:00
will be16:59:59
5.A method called Hora12
that converts to String
the time by concatenating its attributes and returns the string in the 12-hour format ( hh:mm:ss AM/PM
)
AM: (until 12 noon), PM (from 12 to 24 hours)
This is my code, Class Reloj
:
public class Reloj {
int modo,hora, minutos,segundos;
int getmodo(){
return modo;
}
public void setmodo(int modo){
this.modo=modo;
}
int gethora(){
return hora;
}
public void sethora(int hora){
this.hora=hora;
}
public int getminutos(){
return minutos;
}
public void setminutos(int minutos){
this.minutos=minutos;
}
public int getsegundos(){
return segundos;
}
public void setsegundos(int segundos){
this.segundos=segundos;
}
public Reloj(){
modo=24; /*por defecto ponemos 24horas*/
hora=0;
minutos=0;
segundos=0;
}
public Reloj( int h, int m, int s){
this.modo=24;
this.hora=h %24;
this.minutos=m % 60;
this.segundos=s % 60;
}
public void ponerEnHora(int md, int hh, int mm, int ss){
modo=md;
hora=hh % 24;
minutos=mm % 60;
segundos=ss % 60;
}
public void incrementar(){
segundos++;
if (segundos==60){
segundos=0;
minutos++;
if(minutos==60){
minutos=0;
hora=(hora+1)%24;
}
}
}
public void decrementa(){
segundos--;
if(segundos<00){
segundos=59;
minutos--;
if(minutos<00){
minutos=59;
hora=(hora-1) %24;
}
}
}
public String verHora(){
String hms="Son las ";
if (modo==12){//modo 12 horas
hms+=(hora>12)?hora-12:hora;
hms+= ":"+minutos+":"+segundos;
hms+=(hora>=12)?"pm":"am";
}else{//modo 24h
hms+=hora+":"+minutos+":"+segundos;
}
return (hms);
}
}
Clock class MAIN:
public class Relojes {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Reloj reloj1 = new Reloj();
reloj1.ponerEnHora(24,17,10,10);
System.out.println(reloj1.verHora());
reloj1.incrementar();
System.out.println(reloj1.verHora());
reloj1.decrementa();
System.out.println(reloj1.verHora());
}
}
I don't get the hours in 12H mode, everything else works, but it doesn't work for me to print the 12h mode with AM or PM, let's see if you can give me a hand.
All that was left was to call the setModo method of the Clock class and give it 12