斗地主游戏
package com.itheima; public class ArrayTest4 { public static void main(String[] args) { start(); } public static void start() { //创建一个数组,保存54张牌 String[] poker = new String[54]; //准备四种花色 String[] colors = {"♠", "♥", "♣", "♦"}; //准备13张牌 String[] numbers = {"3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A", "2"}; //遍历点数,再遍历花色,利用遍历循环给数组赋值 int index = 0; for(int i = 0; i < numbers.length; i++) { for(int j = 0; j < colors.length; j++) { poker[index++] = colors[j] + numbers[i]; } } //添加大小王 poker[index++] = "小王"; poker[index] = "大王"; System.out.println("牌已经生成完毕"); for(int i = 0; i < poker.length; i++) { System.out.print(poker[i] + "\t"); } System.out.println();//换行 //洗牌,遍历54次,每次遍历随机两张牌交换顺序 for(int i = 0; i < poker.length; i++) { int index1 = (int)(Math.random() * poker.length); int index2 = (int)(Math.random() * poker.length); String temp = poker[index1]; poker[index1] = poker[index2]; poker[index2] = temp; } System.out.println("牌已经洗牌完毕"); for(int i = 0; i < poker.length; i++) { System.out.print(poker[i] + "\t"); } } }ps:定义时定义数组数量,索引时从0开始
二维数组
//二维数组静态定义简单版,类似一维String[][]name={{"张三","王五"},{"刘六","诸葛","司马"},{"橘子","火舞","娜可","李四"}};//索引1:数组名[行索引] String name0 = name[2][2]; System.out.println(name0); //索引2:数组名[行索引][列索引] String[] name1 = name[0]; System.out.println(name[2][2]); //长度访问 System.out.println(name.length);//有三行 --- 3 System.out.println(name[0].length);//第一行有2个 --- 2 //按照二维数组定义顺序打印,包括换行 for(int i = 0; i < name.length; i++) { String[] namexiao = name[i]; for(int j = 0; j < namexiao.length; j++) { System.out.print(namexiao[j] + "\t"); } System.out.println(); }数组重点
数组重点:静态定义,动态定义,索引,长度静态定义
一维
类型[ ] 数组名 = { };二维
类型[ ][ ] 数组名 = { { },{ },{ } };动态定义
一维
动态定义:类型[ ] 数组名 = new 类型[行]二维
类型[ ][ ] 数组名 = new 类型[行][列]索引
一维
索引:数组名[行]二维
数组名[行][列] 二维数组 "数组名[行]" 索引的是二维数组中的某一个一维数组长度
一维
长度:数组名.length二维
长度:数组名.length --- 指的是二维数组中一维数组的个数 二维数组 "数组名[行].length" 的长度是二维数组中的某一个一维数组的长度