Buatlah objek untuk menghitung
nilai faktorial n, kombinasi nr, dan
permutasi nr masing-masing dalam satu
objek.
P
E N Y E L E S A I A N :
(Main.java)
package menghitungfaktorialdenganobjek;
import java.util.*;
public class Main {
public static void main(String[] args) {
int pilih;
Scanner x = new Scanner(System.in);
do {
System.out.println("Menghitung Nilai");
System.out.println("1. Faktorial n");
System.out.println("2. Kombinasi nr");
System.out.println("3. Permutasi nr");
System.out.println("4. Keluar");
System.out.print("Masukkan Pilihan anda (1-4) = ");
pilih=x.nextInt();
if(pilih==1)
{
ObjekX A=new ObjekX();
A.faktorial();
}
else if(pilih==2)
{
ObjekX B=new ObjekX();
B.kombinasi();
}
else if(pilih==3)
{
ObjekX C=new ObjekX();
C.permutasi();
}
} while (pilih>0 && pilih<4);
}
}
(ObjekX.Java)
package menghitungfaktorialdenganobjek;
import java.util.*;
public class ObjekX {
public void faktorial(){
int n = 1;
int i;
Scanner input1 = new Scanner(System.in);
System.out.println("________________________");
System.out.println("Program Hitung Faktorial");
System.out.println("________________________");
System.out.print("Bilangan =
");
int x=input1.nextInt();
if(x>0)
{
for(i=1; i<x; i++)
n=n*(x-i);
n=n*x;
}
else if (x<0)
n=1;
System.out.print("Nilai Faktorial dari " +x+ " adalah
" +n+ "\n");
}
public void kombinasi(){
int n;
int r;
System.out.println("__________________________");
System.out.println("Menghitung Nilai Kombinasi");
System.out.println("__________________________");
Scanner x = new Scanner(System.in);
System.out.print("Masukan bilangan n = ");
n = x.nextInt();
System.out.print("Masukan bilangan r = ");
r = x.nextInt();
int o=1;
int s=1;
int p, q;
for(p=n;p>=1;p--) {
o*=p;
}
q=(n-r);
for(r=q;r>=1;r--) {
s*=r;
}
System.out.println(n+"P"+r+" = "+(o/s));
}
public void permutasi(){
int n;
int r;
int fak1 = 1;
int fak3 = 1;
int permutasi;
int k=1;
int i=1;
System.out.println("__________________________");
System.out.println("Menghitung Nilai Permutasi");
System.out.println("__________________________");
Scanner x = new Scanner(System.in);
System.out.print("Masukan bilangan n = ");
n = x.nextInt();
System.out.print("Masukan bilangan r = ");
r = x.nextInt();
for(i=1; i<=n ; i++)
{
fak1=fak1*i;
}
for(k=1; k<=r; k++)
{
fak3=fak3*k;
}
permutasi = fak1/fak3;
System.out.println("\nHasil Permutasi = "+permutasi);
}
}
H A S I L :
0 komentar:
Post a Comment