数组的基础练习

数组的创建方式

int[] nums;
int nums1[];
int[] nums2 = new int[5];
int[] nums4 = new int[]{5,4,6,3,2,};

课后练习
1、ABCD(条件:AB永远不在一起,CD永远在一起)有多少种组合?打印出所有组合。

static int one(){
	char[] letter = {'A','D','C','B'};
	int num =0; 
	for(int a = 0;a<4;a++){	
		if(a==0||a==3){
			for(int c = 1;c<3;c++){
				if(c==2||c==1){
					System.out.println("-"+letter[a]+letter[c]+letter[3-c]+letter[3-a]);
					num++;
				}	
			}
		}
	}
	return num;
}

2、有一个4个长度的数组,每个位置装有0-9之间的随机数字,有10次输入一个4位整数的机会,来猜每个位置的上的数,每次输入数字以后都要给出提示,正确几个、 错误几个,只有位置和数字完全正确才算正确,其他情况全视为错误。

static void two(){
		//需要猜测的四位数
		int[] nums1 = {1,5,2,3};
		Scanner scan = new Scanner(System.in);
		for (int x = 0;x<10;x++){
			System.out.print("请输入你猜测的数字:");
			//将输入转换为数组
			int[] nums2 = int_array(scan.nextInt());
			
			//判断是否相同
			int result = panduan(nums1,nums2);

			if(result==-1){
				System.out.print("恭喜你全部正确");
				break;
			}
			else{
				System.out.println("你第 "+(x+1)+" 次猜对 "+result+" 个数");
				if(result==4)
					System.out.println("你数字全部才对但是顺序不对");
			}
			if(x+1==10)
				System.out.print("猜错了,没有机会了");
		}
	}

函数作用,比较两个数组中相同数字的个数,返回正确个数,如果两个数组的索引和索引对应的值都相等,就返回-1

static int panduan(int[] nums1,int[] nums2){
		//正确个数
		int count = 0;
		//完全正确个数
		int real_count = 0;
		for(int x = 0; x<nums1.length;x++)
		{
			for (int y = 0;y<nums2.length;y++)
			{
				if(nums1[x] == nums2[y]){
					count++;
					if(x==y)
						real_count++;
				}
			}
		}
		if(real_count==4)
			return -1;
		return count;
	}

函数作用,将输入的四位数转换为数组返回

	static int[] int_array(int num){
		int[] nums = new int[4];
		nums[0] = num / 1000;
		nums[1] = num % 1000 / 100;
		nums[2] = num % 100 / 10 ;
		nums[3] = num % 10;
		return nums;
	}

by 2019年10月18日

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值