
Kita akan coba membuat fungsi untuk menghitung umur kita di planet lain dengan java.
Disini kita akan coba menghitung umur kita di 4 planet (“Mercury”, “Venus”, “Jupiter”, “Saturn”), dengan nilai konstanta (87.96, 224.68, 11.862, 29.456).
Untuk menghitung umur kita memerlukan 2 fungsi, berikut syntax untuk fungsi pertama:
1 2 3 4 5 6 |
private String calculateAgeOnPlanet(double ageInEarth, int planetIndex) { String[] namePlanet = new String[] {"Mercury","Venus","Jupiter","Saturn"}; double[] dayPlanet = new double[] {87.96, 224.68, 11.862, 29.456}; return "Age " + ageInEarth + " in earth = age " + getAgeOnPlanet(ageInEarth, dayPlanet[planetIndex]) + " in " + namePlanet[planetIndex]; } |
Berikut fungsi kedua:
1 2 3 |
private double getAgeOnPlanet(double ageInEarth, double dayPlanetBaseEarth) { return ageInEarth * 365 / dayPlanetBaseEarth; } |
Berikut cara memanggil fungsi diatas:
1 2 3 4 |
double umurKita = 26; for (int i = 0; i < 4; i++) { System.out.println(calculateAgeOnPlanet1(umurKita, i)); } |
Hasil:
Age 26.0 in earth = age 107.8899499772624 in Mercury
Age 26.0 in earth = age 42.237849385793126 in Venus
Age 26.0 in earth = age 800.0337211262856 in Jupiter
Age 26.0 in earth = age 322.17544812601847 in Saturn
Semoga membantu