Ví dụ về hàm trong Java
public class baitap {
// Ham nhap mang
public static void input(int a[]) {
Scanner objSc = new Scanner(System.in);
for (int i = 0; i < a.length; i++) {
System.out.print("a[" + i + "]=");
a[i] = objSc.nextInt();
}
}
// Ham hien thi mang
public static void output(int a[]) {
for (int i = 0; i < a.length; i++)
System.out.print("a[" + i + "]=" + a[i] + " ");
System.out.println();
}
// Tim kiem 1 phan tu trong mang
public static int search(int a[], int x) {
for (int vt = 0; vt < a.length; vt++)
if ((a[vt] == x))
return vt;
return -1;
}
// Ham kiem tra so nguyen to
public static int laSNT(int n) {
if (n < 2)
return 0;
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
return 0;
}
}
return 1;
}
// Ham kiem tra tinh chat mang
public static int check(int a[]) {
for (int i = 0; i < a.length; i++)
if (laSNT(a[i]) == 0)
return 0;
return 1;
}
// Ham tach thanh mang cac so la nguyen to va khong phai nguyen to
public static void tachGhep(int a[], int b[], int c[], int d[]) {
int nc = 0;
int nb = 0;
int nd=0;
for (int i = 0; i < a.length; i++) {
if (laSNT(a[i]) == 1) {
b[nb] = a[i];
nb++;
} else {
c[nc] = a[i];
nc++;
}
}
System.out.println("Mang cac so nguyen to");
for (int i = 0; i < nb; i++)
System.out.print(b[i] + " ");
System.out.println();
System.out.println("Cac so khong phai la so nguyen to");
for (int i = 0; i < nc; i++)
System.out.print(c[i] + " ");
System.out.println();
//Ghep 2 mang
for (int i = 0; i < nb; i++) {
d[nd]=b[i];
nd++;
}
for(int i=0;i
d[nd]=c[i];
nd++;
}
System.out.println("Mang sau ghi ghep!");
for(int i=0;i
System.out.print(d[i]+" ");
}
}
//Sap xep mang theo thu tu giam dan
public static void sortASC(int a[]) {
for(int i=0;i
for(int j=i+1;j
if(a[i]>a[j]) {
int tmp;
tmp = a[i];
a[i]=a[j];
a[j]=tmp;
}
}
}
//Ham tim gia tri lon nhat trong mang
public static void maxArray(int a[]) {
int max = a[0];
int k=0;
for(int i=1;i
max=a[i];
k=i;
}
}
System.out.println();
System.out.println("So lon nhat:"+max);
System.out.println("Tai vi tri:"+k);
}
public static void main(String[] args) {
int a[] = new int[5];
int b[] = new int[5];
int c[] = new int[5];
int d[] =new int[5];
int x;
input(a);
System.out.println("Mang vua nhap");
output(a);
Scanner objSc = new Scanner(System.in);
System.out.print("Nhap vao so can tim?");
x = objSc.nextInt();
if (search(a, x) == -1)
System.out.println("Khong tim thay!!!");
else
System.out.println("Vi tri tim thay:" + search(a, x));
if (check(a) == 1)
System.out.println("Mang chua cac so nguyen to!");
else
System.out.println("Khong phai toan bo la cac so nguyen to");
sortASC(a);
System.out.println("Mang sau khi sap xep");
System.out.println();
output(a);
tachGhep(a, b, c,d);
maxArray(a);
}
}
Trương Đình Huy
» Tin mới nhất:
» Các tin khác: