Is there anyway to do this program a different way without using Intger.parseInt
ID: 3840887 • Letter: I
Question
Is there anyway to do this program a different way without using Intger.parseInt like so
public class Clock {
public int getHours(){
String s=new java.util.Date().toString();
int hour= Integer.parseInt(s.substring(11,13));
return hour;
}
public int getMinutes(){
String s=new java.util.Date().toString();
int minute= Integer.parseInt(s.substring(14,16));
return minute;
}
public String getTime(){
String date = "";
String hr = Integer.toString(getHours());
if(hr.length() == 1)
date = date + "0"+hr+":";
else
date = date +hr+":";
String min = Integer.toString(getMinutes());
if(min.length() == 1)
date = date + "0"+min;
else
date = date +min;
return date;
}
}
############ WorldClock.java ######
public class WorldClock extends Clock{
private int offset;
public WorldClock(int offset) {
this.offset = offset;
}
public int getHours(){
String s=new java.util.Date().toString();
int hour= Integer.parseInt(s.substring(11,13));
hour = (hour + offset)%24;
return hour;
}
public int getMinutes(){
String s=new java.util.Date().toString();
int minute= Integer.parseInt(s.substring(14,16));
return minute;
}
}
JAVA OOP
Explanation / Answer
public class Clock {
public int getHours() {
int hour = new java.util.Date().getHours();
return hour;
}
public int getMinutes() {
int minute = new java.util.Date().getMinutes();
return minute;
}
public String getTime() {
String date = "";
String hr = Integer.toString(getHours());
if (hr.length() == 1)
date = date + "0" + hr + ":";
else
date = date + hr + ":";
String min = Integer.toString(getMinutes());
if (min.length() == 1)
date = date + "0" + min;
else
date = date + min;
return date;
}
}
public class WorldClock extends Clock {
private int offset;
public WorldClock(int offset) {
this.offset = offset;
}
public int getHours() {
int hour = new java.util.Date().getHours();
hour = (hour + offset) % 24;
return hour;
}
public int getMinutes() {
int minute = new java.util.Date().getMinutes();
return minute;
}
}
public class TestWorldClock {
/**
* @param args
*/
public static void main(String[] args) {
WorldClock clock = new WorldClock(0);
System.out.println("Time=" + clock.getTime());
}
}
OUTPUT:
Time=06:47
NOTE: we can use the getHours(), getMinutes() of java.util.Date() class for getting hours and minutes;
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.