妳去
我所做的是添加
java.util.Random类,而不是
Math.random()生成随机数。
使用可以在
ArrayList需要时分配更多内存的情况下分配更大的内存,以存储小于或大于499的值。
public static void main(String[] args){ Scanner in = new Scanner(System.in); System.out.print(" How many random numbers between 0 – 999 do you want? "); int varde = in.nextInt(); System.out.println(" "); System.out.println(" this is your numbers:"); Random randomGenerator = new Random(); int randomArray[]=new int[varde]; for(int i = 0; i<varde; i++) {randomArray[i] = randomGenerator.nextInt(1000); System.out.print(randomArray[i]); } int largest = randomArray[0]; for(int x=0; x<randomArray.length; x++){ if(randomArray[x]>largest) largest = randomArray[x]; } System.out.println("Largest no is: "+largest); List<Integer> numbersGreaterThanHalf = new ArrayList<Integer>(); List<Integer> numbersLowerThanHalf = new ArrayList<Integer>(); for(int x=0; x<randomArray.length; x++){ if(randomArray[x]>499) numbersGreaterThanHalf.add(randomArray[x]); else numbersLowerThanHalf.add(randomArray[x]); } System.out.println("these " + numbersLowerThanHalf.length() + "numbers is between 0 – 499"); for(Integer number: numbersLowerThanHalf) { System.out.print(number + " "); } System.out.println("these " + numbersGreaterThanHalf.length() + "numbers is between 500 – 999"); for(Integer number: numbersGreaterThanHalf) { System.out.print(number + " "); }}
没有新的数组实现摘要:
StringBuilder numbersAboveHalf = new StringBuilder(); StringBuilder numberBelowHalf = new StringBuilder(); int countOfNumbersAboveHalf = 0; int countOfNumbersBelowHalf = 0; for(int x=0; x<randomArray.length; x++){ if(randomArray[x]>499){ numbersAboveHalf.append(randomArray[x]).append(" "); ++countOfNumbersAboveHalf; } else{ numbersBelowHalf.append(randomArray[x]).append(" "); ++countOfNumbersBelowHalf; } } System.out.println("these " + countOfNumbersBelowHalf + "numbers is between 0 – 499"); System.out.println(numbersBelowHalf.toString()); System.out.println("these " + countOfNumbersAboveHalf + "numbers is between 500 – 999"); System.out.println(numbersAboveHalf.toString());
这是对数组进行迭代并执行以下 *** 作:
- 计算有500以上的数字和500以下的数字。
- 用数字构建2个字符串。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)