在Java的基础班已经学习六天了,便想着自己定一个需求来将之前的内容整合到一起,也算是个复习。
需求如下:
定义两个数组,数组长度在五到八位之间,元素值在0-9之间,判断两个数组是否相同。
1.先生成数组并赋值,再进行判断。
代码如下:
package baseday6;
import java.util.Random;
public class day6Teat06 {
public static void main(String[] args) {
Random r = new Random();
//定义两个空数组arr,brr
int[] arr = new int[1];
int[] brr = new int[1];
int count = 0;
//对两个数组循环赋值
do {
//随机定义ar长度
int a = r.nextInt(4)+5;
int[] ar = new int[a];
System.out.println("arr长度"+a);
//将ar地址送给arr
arr = ar;
//对arr循环赋值并打印
for (int i = 0; i < arr.length; i++) {
arr[i] = r.nextInt(10);
System.out.print(arr[i] + "\t");
}
//换行
System.out.println(" ");
//随机定义br长度
int b = r.nextInt(4)+5;
int[] br = new int[b];
System.out.println("brr长度"+b);
//将br地址送给brr
brr = br;
//对brr循环赋值并打印
for (int j = 0; j < brr.length; j++) {
brr[j] = r.nextInt(10);
System.out.print(brr[j] + "\t");
}
//换行
System.out.println(" ");
count++;
}
//调用方法判断两个数组是否相同;
while (compare(arr, brr));
//打印两个相同的数组
for(int c = 0; c < arr.length; c++) {
System.out.print(arr[c] + "\t");
}
System.out.println(" ");
for (int d = 0; d < brr.length; d++) {
System.out.print(brr[d] + "\t");
}
System.out.println(" ");
//输出赋值次数
System.out.println("循环次数"+count);
}
public static boolean compare(int[] arr, int[] brr) {
boolean z ;
//判断两数组长度是否相等,若不相等return true
if (arr.length == brr.length) {
//判断数组内的每个元素是否都相等,若不相等return true
for (int i = 0; i < arr.length; i++) {
if (arr[i] == brr[i]) {
//若相等则将false赋值给z
z = false;
} else {
return true;
}
}
} else {
return true;
}
return false;
}
}
2.先生成数组,判断数组长度相同后再进行赋值,赋值同时判断是否相同。
package baseday6;
import java.util.Random;
public class day6Test0602 {
public static void main(String[] args) {
Random r = new Random();
//定义两个空数组arr,brr
int[] arr = new int[1];
int[] brr = new int[1];
int count = 0;
do {
//随机定义ar长度
int a = r.nextInt(4)+5;
int[] ar = new int[a];
//将ar地址送给arr
arr = ar;
//随机定义br长度
int b = r.nextInt(4)+5;
int[] br = new int[b];
//将br地址送给brr
brr = br;
if (arr.length==brr.length) {
System.out.println("数组长度"+a);
for (int i = 0; i < arr.length; i++) {
arr[i] = r.nextInt(10);
brr[i] = r.nextInt(10);
System.out.println("第"+i+"元素"+arr[i]+"\t"+brr[i]);
}
System.out.println(" ");
}
count ++;
}
while (compare(arr,brr));
for(int c = 0; c < arr.length; c++) {
System.out.print(arr[c] + "\t");
}
System.out.println(" ");
for (int d = 0; d < brr.length; d++) {
System.out.print(brr[d] + "\t");
}
System.out.println("循环次数"+count);
}
public static boolean compare(int[] arr, int[] brr) {
boolean z;
for (int i = 0; i < arr.length; i++) {
if (arr.length == brr.length) {
if (brr[i] != arr[i]) {
return true;
} else {
z = false;
}
} else {
return true;
}
}
return false;
}
}
来自一个刚入Java一周小萌新 |
|