Last active
October 14, 2023 02:02
-
-
Save rafirh/13041e9ab27563f40c8f6ddca8c6f731 to your computer and use it in GitHub Desktop.
Konversi Waktu
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Scanner; | |
import java.util.Arrays; | |
public class Solution { | |
public static void main(String[] args) { | |
// Inisialisasi objek Scanner untuk membaca masukan dari pengguna | |
Scanner scanner = new Scanner(System.in); | |
// Membaca masukan waktu dari pengguna sebagai string | |
String waktu = scanner.nextLine(); | |
// Memecah string waktu menjadi array simbol dengan menggunakan regex | |
// Ini akan memisahkan karakter huruf dan angka dalam string waktu | |
String[] simbol = waktu.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)"); | |
// Variabel untuk menyimpan total detik | |
int totalDetik = 0; | |
// Variabel untuk menyimpan simbol huruf saat ini | |
String huruf = ""; | |
// Iterasi melalui array simbol | |
for (int i = 0; i < simbol.length; i++) { | |
if (i % 2 == 0) { | |
// Jika indeks i adalah indeks huruf, maka simpan simbol huruf saat ini | |
huruf = simbol[i].trim(); | |
} else { | |
// Jika indeks i adalah indeks angka, maka konversi angka dan tambahkan ke total detik | |
int jumlah = Integer.parseInt(simbol[i]); | |
totalDetik += jumlah * konversiSimbol(huruf); | |
} | |
} | |
// Menampilkan total detik ke layar | |
System.out.println(totalDetik); | |
} | |
// Metode untuk mengkonversi simbol huruf menjadi jumlah detik | |
public static int konversiSimbol(String simbol) { | |
switch (simbol) { | |
case "T": | |
return 60 * 60 * 24 * 365; // Tahun | |
case "B": | |
return 60 * 60 * 24 * 30; // Bulan | |
case "H": | |
return 60 * 60 * 24; // Hari | |
case "J": | |
return 60 * 60; // Jam | |
case "M": | |
return 60; // Menit | |
default: | |
return 0; // Default jika simbol tidak dikenali | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment