第六周课后作业(4.12)

 

1.定义长度位5的整型数组,输入他们的值,用冒泡排序后输出.

public class zxcvbn {
public static void main(String[] args) {
int[] arr={10,22,42,1,6};
//外层循环控制比较轮数
for(int i=0;i<arr.length-1;i++){
//内层循环控制每轮比较次数
for(int j=0;j<arr.length-1-i;j++){
if(arr[j]>arr[j+1]){
int temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
//遍历数组
for(int i=0;i<arr.length;i++){
System.out.println(arr[i]);
}
}
}

2.定义数组{34,22,35,67,45,66,12,33},输入一个数a,查找在数组中是否存在,如果存在,输出下标,不存在输出"not found"

import java.util.Scanner;
public class zxcvbn {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
int[] arr={34,22,35,67,45,66,12,33};
System.out.println("请输入你要查找的元素");
int element=in.nextInt();
int i,flag=0;
for(i=0;i<arr.length;i++){
if(arr[i]==element){
flag=1;
break;
}
}
if(flag==1){
System.out.println("你要查找的元素的下标为:"+i);
}else{
System.out.println("你要查找的元素不存在");
}
}
}

3.以矩阵的形式输出一个double型二维数组(长度分别为5、4,值自己设定)的值。

public class zxcvbn {
public static void main(String[] args) {
double[][] arr = { { 5, 6, 7,8 }, { 9, 10,11, 12 }, { 14, 15, 16, 17 }, { 19, 20, 21, 22 }, { 1, 2, 3, 4 } };
for (int i = 0; i < arr.length; i++) {
System.out.println();
for (int j = 0; j < arr[i].length; j++) {
System.out.print(arr[i][j] + " ");
}
}
}

}

4.定义一个二维数组(长度分别为3,4,值自己设定),求该二维数组的最大值.

public class zxcvbn {
public static void main(String[] args) {
int arr[][] = { { 11,12, 13 }, { 21, 22, 23 }, { 31,32, 33 }, { 41, 42, 43 } };
int max = arr[0][0];
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j] > max) {
max = arr[i][j];
}
}
}
System.out.println("该二维数组的最大值"+max);
}
}

猜你喜欢

转载自www.cnblogs.com/fanbudufan/p/12684792.html