数组元素的赋值与数组复制
举例1:使用简单数组
public static void arraycp() { int[] array1 = new int[]{2, 3, 5, 7, 11, 13, 17, 19}; int[] array2 = array1; for (int i : array2) { System.out.println(i); } System.out.println("---------------------"); for (int i = 0; i < array2.length; i++) { if (array2[i] % 2 == 0) { array2[i] = i; } } for (int i : array2) { System.out.println(i); } System.out.println("---------------------"); System.out.println(array1 == array2); }
举例2:一个数组,让数组的每个元素去除第一个元素,得到的商作为被除数所在位置的新值。
public static void arraycp1() { int[] array1 = new int[]{2, 3, 5, 7, 11, 13, 17, 19}; for (int i = 0; i < array1.length; i++) { array1[i] = (int) array1[i] / array1[0]; } //遍历 for (int i : array1) { System.out.println(i); } }
举例3:创建一个长度为6的int型数组,要求数组元素的值都在1-30之间,且是随机赋值。同时,要求元素的值各不相同
public static void randomArr() { int[] arr = new int[6]; for (int i = 0; i < arr.length; i++) { arr[i] = (int) (Math.random() * 30) + 1; for (int j = 0; j < i; j++) { if (arr[i] == arr[j]) { i--; break; } } } for (int i1 : arr) { System.out.println(i1); } }
举例4:扑克牌
案例:遍历扑克牌
遍历扑克牌,效果如图所示:
提示:使用两个字符串数组,分别保存花色和点数,再用一个字符串数组保存最后的扑克牌。 String[] hua = {"黑桃","红桃","梅花","方片"}; String[] dian = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
public static void pic() { String[] hua = {"黑桃", "红桃", "梅花", "方片"}; String[] dian = {"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"}; String[] arr = new String[hua.length * dian.length]; int k = 0; for (int i = 0; i < hua.length; i++) { for (int j = 0; j < dian.length; j++) { arr[k++] = hua[i] + dian[j]; } } for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + ", "); if (i % 13 == 12) { System.out.println(); } } }
举例5:回形数
从键盘输入一个整数(1~20) ,则以该数字为矩阵的大小,把1,2,3…n*n 的数字按照顺时针螺旋的形式填入其中。
例如: 输入数字2,则程序输出: 1 2 4 3
输入数字3,则程序输出: 1 2 3 8 9 4 7 6 5 输入数字4, 则程序输出: 1 2 3 4 12 13 14 5 11 16 15 6 10 9 8 7
public static void rectangleNew() { Scanner scanner = new Scanner(System.in); System.out.println("输入一个数字"); int n = scanner.nextInt(); int[][] arr = new int[n][n]; int count = 0; //要显示的数据 int maxX = n - 1; //x轴的最大下标 int maxY = n - 1; //Y轴的最大下标 int minX = 0; //x轴的最小下标 int minY = 0; //Y轴的最小下标 while (minX <= maxX) { for (int x = minX; x <= maxX; x++) { arr[minY][x] = ++count; } minY++; for (int y = minY; y <= maxY; y++) { arr[y][maxX] = ++count; } maxX--; for (int x = maxX; x >= minX; x--) { arr[maxY][x] = ++count; } maxY--; for (int y = maxY; y >= minY; y--) { arr[y][minX] = ++count; } minX++; } for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr.length; j++) { String space = (arr[i][j] + "").length() == 1 ? "0" : ""; System.out.print(space + arr[i][j] + " "); } System.out.println(); } scanner.close(); }