Java method get ()

Im working on the following question:

A 24-hour clock is a 4-digit number, where the leftmost two digits indicate the hour (from 0 to 23, inclusive) and the rightmost two digits indicate the minutes (from 0 to 59, incl.). For example, 2130 expresses half past eight in the evening. Write a class Time for encapsulation time. It must have the following instance methods:

get the time from the keyboard (comes in the form of a four-digit number, for example 2130). You can assume that the number represents the actual time.

My code so far:

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 is how to divide the 4-digit input by hour and minute, all the tips, the tips are appreciated.

+4
source share
2 answers

for an integer x with 4 digits:

 x / 100 - gives the 2 left digits x % 100 - gives the 2 right digits 

EDIT: Assuming that the zeros of the header are silently skipped since 0000 is converted to 0 as an integer and will give hour = 0 (translate to 00), min = 0 (translate to 00) - as expected.

+11
source

Read the input as a String , then use the 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); 
+6
source

All Articles