求数组中基数个数和偶数个数
public class ArrayDemo2{
public static int oddNumber(int a[]){
int num=0;
for(int i=0;i<a.length;i++){
if(a[i]%2!=0){
num++;
}
}
return num;
}
public static int evenNumber(int a[]){
int num=0;
for(int i=0;i<a.length;i++){
if(a[i]%2==0){
num++;
}
}
return num;
}
public static void main(String[] args) {
int arr[]={1,2,3,4,5,6,7};
for(int i=0;i<arr.length;i++){
System.out.print(arr[i]+"\t");
}
System.out.println();
System.out.println("----------------------------------------------------");
System.out.println("数组中偶数个数为:"+evenNumber(arr));
System.out.println("数组中基数个数为:"+oddNumber(arr));
}
}
去掉原数组中的0
public class ArrayTest3{
public static void main(String args[]){
int oldArr[]={1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5};
print(oldArr);
int newArr[]=delZero(oldArr);
print(newArr);
}
public static int[] delZero(int a[]){
int newArr[]=null;
newArr=new int[a.length-4];
int j=0;
for(int i=0;i<a.length;i++){
if(a[i]!=0){
newArr[j]=a[i];
j++;
}
}
return newArr;
}
public static void print(int a[]){
for(int i=0;i<a.length;i++){
System.out.print(a[i]+"\t");
}
System.out.println();
}
}
查询数字是否在数组内
import java.util.Scanner;
public class ArrayTest5{
public static void main(String args[]){
int arr[]={3,1,56,43,2,21,10,24,21,93};
System.out.print("原数组:");
for(int i=0;i<arr.length;i++){
System.out.print(arr[i]+" ");
}
System.out.println();
System.out.println("请输入要查询的数");
Scanner sc=new Scanner(System.in);
int x=sc.nextInt();
boolean a=search(x,arr);
System.out.println(a);
}
public static boolean search(int x,int a[]){
boolean b=false;
for(int i=0;i<a.length;i++){
if(a[i]==x){
b=true;
}
}
return b;
}
}
反向输出一个数组
public class ArrayTest5{
public static void main(String args[]){
int arr[]=new int[10];
for(int i=0;i<arr.length;i++){
arr[i]=i;
System.out.print(arr[i]+" ");
}
System.out.println();
int newArr[]=reverse(arr);
for(int i=0;i<newArr.length;i++){
System.out.print(newArr[i]+" ");
}
}
public static int[] reverse(int a[]){
int newArr[]=new int[10];
int j=9;
for (int i=0;j>=0;i++,j--){
newArr[i]=a[j];
}
return newArr;
}
}