Reputation: 11
I'm trying to convert HH:MM into only minutes and having no luck with it. Any help would be great.
import java.util.Scanner;
public class taskA {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please Specify your time HH:MM");
String Time = scanner.next();
System.out.println("Your time is: " + Time);
String finalTime = (Time * 60);
System.out.println("your final time in minutes is :" + finalTime);
}
}
Upvotes: 1
Views: 59
Reputation: 1
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please Specify your time HH:MM");
String input = scanner.nextLine();
String[] time = input.split("\\:");
int hour = Integer.parseInt(time[0]);
int minutes = Integer.parseInt(time[1]);
System.out.println("Your time is: " + hour + ":" + minutes);
int finalTime = (minutes + hour * 60);
System.out.println("your final time in minutes are :" + finalTime);
}
This should work the way you want it. Youre problem was that you need to work with integers and not strings. So what this code does is to read the next Line and saving it in "input". The next line creates an Array of Strings in which the input gets divided, which workes like this: The method input.split("\:") takes the String "input" and takes all the chars until ":" comes, then it saves the chars in the first index of the Array(time[0]), then takes the rest and saves it in the next index and so on. Now that you know that hours are in the first index and minutes in the second, you can convert them from Strings to integer and then simply multiply the hours by 60 and you get the minutes. I hope i could help you and i apologize if i made some mistakes(not English).
Upvotes: 0
Reputation: 124648
Here's an example that should get you started:
Scanner scanner = new Scanner("12:34").useDelimiter(":");
System.out.println(scanner.nextInt());
System.out.println(scanner.nextInt());
The above outputs:
12 34
Upvotes: 2