Created
January 24, 2019 09:30
-
-
Save bratawisnu/4316fd99569a6e71c4ea57e276fe962a to your computer and use it in GitHub Desktop.
[Tugas kelompok ke-2] Binus - Java Programming
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
package brata.com; | |
import java.util.Scanner; | |
public class TK2_BilanganPrima { | |
public static void main(String[] args) { | |
int choice; | |
while (true) { | |
System.out.println("\nMenu hari ini :\n"); | |
System.out.println("1. Penjumlahan bilangan prima"); | |
System.out.println("2. Jumlah bilangan prima"); | |
System.out.println("3. Exit"); | |
choice = inputIntegerWithValidation("\nMasukkan Pilihan Anda: "); | |
switch (choice) { | |
case 1: | |
BilanganPrima("penjumlahan"); | |
break; | |
case 2: | |
BilanganPrima("jumlah"); | |
break; | |
case 3: | |
System.exit(0); | |
break; | |
default: | |
System.out.println("Pilihan Anda salah!"); | |
break; | |
} | |
} | |
} | |
private static void BilanganPrima(String choice) { | |
System.out.println("============================================="); | |
int bil1 = inputIntegerWithValidation("Masukkan bilangan 1 : "); | |
int bil2 = inputIntegerWithValidation("Masukkan bilangan 2 : "); | |
System.out.println("============================================="); | |
System.out.println("\nBilangan Prima antara " + bil1 + " dan " + bil2 + " adalah :"); | |
int jumlahPrima = 0; | |
for (int i = bil1; i <= bil2; i++) { | |
int bilPrima = 0; | |
for (int j = 1; j <= i; j++) { | |
if (i % j == 0) | |
bilPrima = bilPrima + 1; | |
} | |
if (bilPrima == 2) { | |
System.out.print(i + " "); | |
if (choice.equals("penjumlahan")) { | |
jumlahPrima = jumlahPrima + i; | |
}else { | |
jumlahPrima++; | |
} | |
} | |
} | |
System.out.println("\nPenjumlahan Bilangan Prima " + jumlahPrima); | |
} | |
// TODO: Method input data integer dengan validasi | |
private static Integer inputIntegerWithValidation(String strLabel) { | |
Scanner sc = new Scanner(System.in); | |
int value = 0; | |
do { | |
System.out.print(strLabel); | |
if (sc.hasNextInt()) { | |
value = sc.nextInt(); | |
return value; | |
} else { | |
System.out.print("Input salah, "); | |
sc.next(); | |
} | |
} while (value == 0); | |
return value; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment