Java基础题(2)

题目:

分析以下需求,并用代码实现
(1).创建两个长度为10的数组,数组内元素为随机生成的、不重复的 1-100之间的整数,
(2).定义一个方法,传入两个数组,函数中将两个数组不同的元素拼接成一个字符串,
并且将该字符串以及字符串的长度输出到控制台上;
如果没有则输出"对不起两个数组的所有元素均相同"

代码:
 1 import java.util.Random;
 2 
 3     public static void main(String[] args) {
 4         int[] arr = new int[10];
 5         int[] arr1 = new int[10];
 6         int[] a = renew(arr);
 7         System.out.println("第一个数组:");
 8         bianli(a);
 9         int[] a1 = renew(arr1);
10         System.out.println("第二个数组:");
11         bianli(a1);
12         different(a,a1);//查找不同的元素
13     }
14 
15     //判断是否相同并拼接成一个字符串输出
16     public static void different(int[] a,int[] b){
17         String str = "";
18         for (int i = 0; i < a.length; i++) {
19             if (chongfu(b,a[i]))
20                 str+=a[i];//遍历,将a不重复的数据放入str中
21         }
22         for (int i = 0; i < b.length; i++) {
23             if(chongfu(a,b[i]))
24             str+=b[i];////brr找与arr中不同的元素
25         }
26         if (str.length()<1)
27             System.out.println("对不起两个数组的所有元素均相同");
28          else
29             System.out.println(str+"\n字符串长度:"+str.length());
30 
31 
32     }
33     //随机生成并且赋值
34     public static int[] renew(int[] a) {
35         Random re = new Random();
36         for (int i = 0; i < 10; i++) {
37             //随机获取数据填入
38             int num = re.nextInt(100) + 1;
39             if (chongfu(a, num))
40                 a[i] = num;//不相等则负值
41             else {
42                 //相等则。指针回到上一个位置,舍弃当前相同数据
43                 i--;
44             }
45         }
46         return a;
47     }
48 
49     //检查输入的数据是否在数组内有相等的数据
50     public static boolean chongfu(int[] a, int num) {
51         int count = 0;
52         for (int i = 0; i < a.length; i++) {
53             if (a[i] == num) {
54                 count++;//相等,计数器加一,并直接跳出
55                 break;
56             }
57         }
58         if (count > 0)
59             return false;
60         else
61             return true;
62     }
63 
64     //遍历输出数组
65     public static void bianli(int[] arr) {
66         System.out.print("[");
67         for (int i = 0;i<arr.length;i++) {
68             if (i==arr.length-1){
69                 System.out.print(arr[i]+"]\n");
70             } else {
71                 System.out.print(arr[i] + ",");
72             }
73         }
74     }

猜你喜欢

转载自www.cnblogs.com/neojoker/p/10662905.html