作业1:
1、利用方法重载,
写三个方法,分别求出int类型绝对值,float类型绝对值和double类型绝对值
结果:
代码部分:
public class AbsoluteValue {
public static void main(String[] args) {
//1、利用方法重载,
//写三个方法,分别求出int类型绝对值,float类型绝对值和double类型绝对值
int i = 25646;
float f = -56.5f;
double d = 354.5849;
System.out.println("变量i是:"+i+" 变量i的绝对值是:"+abs(i));
System.out.println("变量f是:"+f+" 变量f的绝对值是:"+abs(f));
System.out.println("变量d是:"+d+" 变量d的绝对值是:"+abs(d));
}
public static int abs(int i){ //int类型的绝对值
return i = Math.abs(i);
}
public static float abs(float f){ //float类型的绝对值
return f = Math.abs(f);
}
public static double abs(double d){ //double类型的绝对值
return d = Math.abs(d);
}
}
作业2:
3、将下面给定的数组转置输出
例如 原数组: 1,2,3,4,5,6 转置之后的数组: 6,5,4,3,2,1
结果:
代码部分:
public class SortArr {
public static void main(String[] args) {
// 3、将下面给定的数组转置输出
//例如 原数组: 1,2,3,4,5,6 转置之后的数组: 6,5,4,3,2,1
int [] i = {1,2,3,4,5,6}; //原数组
//用冒泡排序 从大到小排列
for (int j = 0; j < i.length-1; j++) {
for (int k = 0; k < i.length-1-j; k++) {
int a = 0; //空杯
if(i[k]<i[k+1]){
a = i[k+1];
i[k+1] = i[k];
i[k] = a;
}
}
}
//输出排完序数组第一位到最后一位的每一个数值
System.out.println("转置后的数组:");
for (int b = 0; b < i.length; b++) {
System.out.print(i[b]+" ");
}
}
}
作业3:
现在有如下2个数组
数组A: “1,7,5,7,9,2,21,13,45”
数组B: “2,5,8,14,21”
将俩个数组合并为数组C,按顺序排列输出
结果:
代码部分:
public class Merge {
public static void main(String[] args) {
/*
* 4、现在有如下2个数组
* 数组A: “1,7,5,7,9,2,21,13,45”
* 数组B: “2,5,8,14,21”
* 将俩个数组合并为数组C,按顺序排列输出
*
*/
int [] a = {1,7,5,7,9,2,21,13,45}; //创建一个数组a直接给值
int [] b = {2,5,8,14,21}; //创建一个数组b直接给值
int [] c = new int [a.length+b.length]; //创建一个数组c c数组的长度是a数组长度+b数组长度
System.arraycopy(a, 0, c, 0, a.length); //把a数组复制到c数组 从第一位开始
System.arraycopy(b, 0, c, a.length, b.length);//把b数组复制的c数组 从a的后面的第一位开始
//用冒泡排序 把数组c从小到大排列
for (int i = 0; i < c.length-1; i++) {
for (int j = 0; j < c.length-1-i; j++) {
int x = 0;
if(c[j]>c[j+1]){
x = c[j+1];
c[j+1] = c[j];
c[j] = x;
}
}
}
//输出排序后的数组c
System.out.println("从小到大排序输出:");
for (int k = 0; k < c.length; k++) {
System.out.print(c[k]+" ");
}
}
}