数组找重复算法demo.
从吃完晚饭折腾到晚上.还在完善中...
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; public class FindNumber { @SuppressWarnings("resource") public static void main(String[] args) { List<Integer> arraylist1 = new ArrayList<Integer>(); List<Integer> arraylist2 = new ArrayList<Integer>(); List<Integer> replacedindexlist = new ArrayList<Integer>(); int arraylength = 0; int repeatednumber = 0; // Scanner sc = new Scanner(System.in); // n = sc.nextInt(); // 输入异常改进 // 这里一定要将控制状态标志的Scanner对象放入while循环内.否则第一次输入异常后进入死循环! boolean flags1 = false; while (!flags1) { System.out.println("请输入数组元素个数:"); Scanner sc1 = new Scanner(System.in); boolean flagsn = sc1.hasNextInt(); if (flagsn) { arraylength = sc1.nextInt(); boolean flagsm = false; flagsm: while (!flagsm) { System.out.println("请输入重复数字个数:"); Scanner sc2 = new Scanner(System.in); flagsm = sc2.hasNextInt(); if (flagsm) { repeatednumber = sc2.nextInt(); if(repeatednumber<=arraylength){ flags1 = true; }else{ System.out.println("重复数字个数不得大于数组长度!"); break flagsm; } } else { System.out.println("输入整数!"); } } } else { System.out.println("输入整数!"); } } int arraylengthcount = 0; while (arraylengthcount < arraylength) { Integer randomnumber = (int) (Math.random() * arraylength + 1); if (!arraylist1.contains(randomnumber)) { arraylist1.add(randomnumber); arraylengthcount++; } } System.out.println("生成的数组:" + Arrays.toString(arraylist1.toArray())); int repeatednumbercount = 0; while (repeatednumbercount < repeatednumber) { // arraylist1.set(replacedindex,repeatednumber); // n较小时可能没有重复的数字,改进 int randomnumber = (int) (Math.random() * arraylength + 1); int replacedindex = (int) (Math.random() * arraylength); if (!replacedindexlist.contains(replacedindex)) { replacedindexlist.add(replacedindex); arraylist1.set(replacedindex, randomnumber); repeatednumbercount++; } } // System.out.println("数组列表长度:"+arraylist.size()); for (int i : arraylist1) { if (!arraylist2.contains(i)) { arraylist2.add(i); } else { System.out.println("找到你啦哈哈:" + i); } } // System.out.println("数组列表1长度:" + arraylist1.size()); System.out.println("含有重复元素的数组:" + Arrays.toString(arraylist1.toArray())); // System.out.println("数组列表2长度:" + arraylist2.size()); // System.out.println("数组列表2:" + Arrays.toString(arraylist2.toArray())); } }
时间: 2024-10-23 11:37:58