JAVA练习:4.数组1.2——遍历与复制
本帖最后由 划句顾 于 2023-3-5 19:47 编辑实验要求:1.编写一个java应用程序
2.输出数组a的全部元素,并将数组a的全部或部分元素复制到其他数组中
3.改变其他数组的元素的值,再输出数组a的全部元素。
本次实验需要调用Arrays类的三个方法:
1.遍历数组
public static String toString(int[] a)
可以得到参数指定的一维数组。
2.复制数组
①public static double[] copyOf(double[] original,int newLength)
如果新数组长度大于原数组长度,copyOf()方法返回的新数组的第newLength索引后的元素取默认值即0;
②public static double[] copyOfRange(double[] original,int from,int to)
将索引from至to-1的元素复制到一个新数组中,并返回这个新数组。
运行结果如下:
package array;
import java.util.Arrays; //这个要记得写
public class CopyArray {
public static void main(String[] args) {
int [] a = {1,2,3,4,500,600,700,800};
int [] b,c,d; // 等价写法: int a[],b[],c[];
System.out.println("a="+Arrays.toString(a));
b = Arrays.copyOf(a,a.length);
System.out.println("b="+Arrays.toString(b));
c = Arrays.copyOf(a,4);
System.out.println("c="+Arrays.toString(c));
d = Arrays.copyOfRange(a,4,a.length);
System.out.println("d="+Arrays.toString(d));
c=-100;
d=-200;
System.out.println("a="+Arrays.toString(a));
System.out.println();
System.out.println("修改后的c为"+Arrays.toString(c));
System.out.println("修改后的d为"+Arrays.toString(d));
}
}
static/image/hrline/5.gif
在c=-100;之后增加语句:
int [] tom = Arrays.copyOf(c,6);
System.out.println("tom="+Arrays.toString(tom));
运行结果如下:
package array;
import java.util.Arrays;
public class CopyArray {
public static void main(String[] args) {
int [] a = {1,2,3,4,500,600,700,800};
int [] b,c,d; // 等价写法: int a[],b[],c[];
System.out.println("a="+Arrays.toString(a));
b = Arrays.copyOf(a,a.length);
System.out.println("b="+Arrays.toString(b));
c = Arrays.copyOf(a,4);
System.out.println("c="+Arrays.toString(c));
d = Arrays.copyOfRange(a,4,a.length);
System.out.println("d="+Arrays.toString(d));
c=-100;
//新加的代码如下:
int [] tom = Arrays.copyOf(c,6);
System.out.println("tom="+Arrays.toString(tom));
System.out.println();
d=-200;
System.out.println("a="+Arrays.toString(a));
System.out.println();
System.out.println("修改后的c为"+Arrays.toString(c));
System.out.println("修改后的d为"+Arrays.toString(d));
}
}
static/image/hrline/5.gif
在System.out.println("a="+Arrays.toString(a)); 之后增加语句:
int [] jerry = Arrays.copyOfRange(d,1,8);
System.out.println("jerry="+Arrays.toString(jerry));
运行结果如下:
package array;
import java.util.Arrays;
public class CopyArray {
public static void main(String[] args) {
int [] a = {1,2,3,4,500,600,700,800};
int [] b,c,d; // 等价写法: int a[],b[],c[];
System.out.println("a="+Arrays.toString(a));
b = Arrays.copyOf(a,a.length);
System.out.println("b="+Arrays.toString(b));
c = Arrays.copyOf(a,4);
System.out.println("c="+Arrays.toString(c));
d = Arrays.copyOfRange(a,4,a.length);
System.out.println("d="+Arrays.toString(d));
c=-100;
d=-200;
System.out.println("a="+Arrays.toString(a));
//新加的代码如下:
int [] jerry = Arrays.copyOfRange(d,1,8);
System.out.println("jerry="+Arrays.toString(jerry));
System.out.println();
System.out.println("修改后的c为"+Arrays.toString(c));
System.out.println("修改后的d为"+Arrays.toString(d));
}
}
页:
[1]