Java开发实战经典—第4章课后答案

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

public class ArrayExecDemo01{

public static void main(String args[]){

int x[] = {1,2,34,4,5,6,7,8,89,8,3,234,24,24,24,24,42,22,43,45,78} ;

int sum1 = 0 ; // 保存奇数个数

int sum2 = 0 ; // 保存偶数个数

for(int i=0;i

if(x[i]%2==0){

sum2++ ;

}else{

sum1++ ;

}

}

System.out.println("奇数的个数是:" + sum1) ;

System.out.println("偶数的个数是:" + sum2) ;

}

}

2

public class ArrayExecDemo02{

public static void main(String args[]){

int oldArr[] = {1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5} ;

int newArr[] = new int[nozeroCount(oldArr)] ;

fillArray(oldArr,newArr) ;

print(newArr) ;

}

public static void print(int x[]){

for(int y : x){

System.out.print(y + "、") ;

}

}

public static void fillArray(int t1[],int t2[]){

int foot = 0 ;

for(int x=0;x

if(t1[x]!=0){

t2[foot] = t1[x] ;

foot++ ; // 修改下标

}

}

}

public static int nozeroCount(int temp[]){

int sum = 0 ;

for(int x=0;x

if(temp[x]!=0){

sum++ ; // 求出不为0的整数的个数

}

return sum ;

}

}

3

public class ArrayExecDemo03{

public static void main(String args[]){

int oldArr[] = {1,3,4,5,11,67,6,6,22,5,4,7,6,7,9,5} ;

int result[] = {0,0,0} ; // 定义一个数组,数组中的第一个元素保存sum、第二个保存max、第三个保存min

result(oldArr,result) ;

System.out.println("数组和是:" + result[0]) ;

System.out.println("最大值是:" + result[1]) ;

System.out.println("最小值是:" + result[2]) ;

}

public static void result(int x[],int res[]){

res[1] = x[0] ; // 第一个元素为最大值

res[2] = x[0] ; // 第一个元素为最小值

for(int i=0;i

res[0] += x[i] ;

if(res[1]

res[1] = x[i] ;

}

if(res[2]>x[i]){

res[2] = x[i] ;

}

}

}

}

4

public class ArrayExecDemo04{

public static void main(String args[]){

int oldArr[] = {1,3,4,5,11,67,6,6,22,5,4,7,6,7,9,5} ;

System.out.println(search(oldArr,33)?"数字已查到!":"数字未查到!") ;

}

public static boolean search(int x[],int val){

boolean flag = false ; // 默认表示没有此内容

for(int i=0;i

if(x[i]==val){

flag = true ;

break ;

}

return flag ;

}

}

5

public class ArrayExecDemo05{

public static void main(String args[]){

int temp[] = new int[10];

init(temp) ;

print(temp) ;

reverse(temp) ;

System.out.println() ;

print(temp) ;

}

public static void reverse(int x[]){

int foot = 0 ;

int head = 0 ;

if(x.length%2==0){

foot = x.length / 2 ; // 求出中间的元素位置

head = foot - 1 ; // 求从前面开始计算的个数

for(int i=0;i

int temp = x[head] ;

x[head] = x[foot] ;

x[foot] = temp ;

head-- ;

foot++ ;

}

}else{ // 如果是奇数个数中间正好存在一个中间点foot = x.length / 2 ;

head = foot ;

for(int i=0;i

int temp = x[head] ;

x[head] = x[foot] ;

x[foot] = temp ;

head-- ;

foot++ ;

}

}

}

public static void init(int x[]){

for(int i=0;i

x[i] = i ;

}

}

相关文档
最新文档