JAVA-1.4-homework
/*1.定义长度位5的整型数组,输入他们的值,用冒泡排序后输出. */ package study; import java.util.*; public class homework { public static void main(String[] args) { System.out.println("请输入五个数(用空格或者换行分隔开):"); Scanner input=new Scanner(System.in); int []a=new int[5]; int t=0; for (int i = 0; i < a.length; i++) { a[i]=input.nextInt(); } for (int i = 0; i < a.length-1; i++) { for (int j = 0; j < a.length-1-i; j++) { if(a[j]>a[j+1]) { t=a[j]; a[j]=a[j+1]; a[j+1]=t; } } } for (int i = 0; i < a.length; i++) { System.out.print(a[i]+" "); } } }
/*2.定义数组{34,22,35,67,45,66,12,33},输入一个数a, * 查找在数组中是否存在,如果存在,输出下标,不存在输出"not found" */ package study; import java.util.*; public class homework { public static void main(String[] args) { System.out.print("请输入一个数(查找它是否存在于数组中):"); Scanner input=new Scanner(System.in); int []a={34,22,35,67,45,66,12,33}; int t=input.nextInt(); int b=-1; for (int i = 0; i < a.length; i++) { if(t==a[i]) { b=i; } } if(b>-1) { System.out.println("数组中存在,下标是:"+b); }else { System.out.println("not found"); } } }
/*3.以矩阵的形式输出一个double型二维数组(长度分别为5、4,值自己设定)的值。 */
//错误提示:二维数组长度为5,4的定义为a[5][4],正确代码在页尾。 package study; import java.util.*; public class homework { public static void main(String[] args) { double[][] a= {{4.2,5.6,7.0,5.5,12.0},{1.2,6.5,7.9,85.6,4.8}, {8.88,41.2,12.3,5.3,1.11},{4.5,8.5,7.9,32.4,58.8}}; for (int i = 0; i < a.length; i++) { for (int j = 0; j < 5; j++) { System.out.print(a[i][j]+"\t"); } System.out.print("\n"); } } }
/*4.定义一个二维数组(长度分别为3,4,值自己设定),求该二维数组的最大值. */
//错误提示:二维数组长度为3,4的定义为a[3][4],正确代码在页尾。 package study; import java.util.*; public class homework { public static void main(String[] args) { double[][] a= {{4.2,5.6,7.0},{1.2,6.5,7.9}, {12.3,5.3,1.11},{7.9,32.4,58.8}}; double max1=0.0,max2=0.0; for (int i = 0; i < a.length; i++) { for (int j = 0; j < 3; j++) { for (int h = j+1; h < 3; h++) { if(a[i][j]>a[i][h]) { max1=a[i][j]; }else { max1=a[i][h]; } } } if(max1>max2) { max2=max1; } } System.out.println(max2); } }
/*3.以矩阵的形式输出一个double型二维数组(长度分别为5、4,值自己设定)的值。 */ //更正: package study; import java.util.*; public class homework { public static void main(String[] args) { double[][] a= {{4.2,5.6,7.0,5.5},{1.2,6.5,7.9,85.6}, {8.88,41.2,12.3,5.3},{4.5,8.5,7.9,32.4},{12.0,4.8,1.11,58.8}}; for (int i = 0; i < a.length; i++) { for (int j = 0; j < 4; j++) { System.out.print(a[i][j]+"\t"); } System.out.print("\n"); } } }
/*4.定义一个二维数组(长度分别为3,4,值自己设定),求该二维数组的最大值. */ //更正: package study; import java.util.*; public class homework { public static void main(String[] args) { double[][] a= {{4.2,5.6,7.0,3.5},{1.2,6.5,7.9,7.8}, {12.3,5.3,1.11,99.9}}; double max1=0.0,max2=0.0; for (int i = 0; i < a.length; i++) { for (int j = 0; j < 4; j++) { for (int h = j+1; h < 4; h++) { if(a[i][j]>a[i][h]) { max1=a[i][j]; }else { max1=a[i][h]; } } } if(max1>max2) { max2=max1; } } System.out.println(max2); } }