Im working on the following question:
A time by the 24-hour clock is a 4-digit number where the leftmost two digits denote the hour (0 to 23, incl.) and the rightmost two digits denote the minutes (0 to 59, incl.). For example, 2130 expresses half-past nine in the evening. Write a class Time to encapsulate a time. It should have the following instance methods:
get to read a time from the keyboard (supplied as a four-digit number e.g. 2130). You may assume the number represents a valid time.
My code so far is:
import java.util.Scanner;
import java.io.*;
class Time {
private double hour, min;
Scanner scanner = new Scanner(System.in);
Time() {
hour = 00;
min = 00;
}
Time(double h, double m) {
hour = h;
min = m;
}
void get() {
System.out.println("Please enter a time in 24 hour format: ");
double x = scanner.nextDouble();
hour = x / 100;
min = x % 100;
System.out.println("The time is " + hour + ":" + min);
}
public String toString() {
return "Time: " + hour + min;
}
}
The problem I have is how to split the 4 digit input into hour and minute, all advice, tips appreciated.
for an integer x
with 4 digits:
x / 100 - gives the 2 left digits
x % 100 - gives the 2 right digits
EDIT: Assuming here the heading zeros are silently omitted, since 0000 is translated to 0 as an integer, and will yield hour=0 (translated to 00), min=0 (translated to 00) - as it supposed to.
Read in the input as a String
then use substring()
method to get the individual hours and minutes:
String s=scanner.nextLine();
String hours=s.substring(0,2);//hour
String minutes=s.substring(2,4);//min
System.out.println("The time is " + hours + ":" + minutes);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With