打印数组中设置值之间的所有数字

打印数组中设置值之间的所有数字,第1张

打印数组中设置值之间的所有数字

妳去

我所做的是添加

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个字符串。


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5142210.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-17
下一篇 2022-11-17

发表评论

登录后才能评论

评论列表(0条)

保存