题目:
使用java.lang.Math类,生成100个0到99之间的随机整数,找出它们之中的最大者和最小者,并统计大于50的整数个数
已有答案:
http://jythoner.javaeye.com/blog/322336?page=1#comments
另答:
/** * */ package math; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Random; /** * @author daniel zhou * */ public class RandomTest { /** * Create 100 random numbers, get min & max number, sun up the number of >50 * @param args */ public static void main(String[] args) { /** * Here main show how to create an random number in some scope // get random by java.lang.Math double random = Math.random()*100; int in=(int) random; System.out.println(random); System.out.println(in); // get random by java.util.Random Random ra=new Random(); System.out.println(ra.nextInt(100)); **/ //create 100 random number ArrayList<Integer> arraylist=new ArrayList<Integer>(); Random rand=new Random(); int total_50=0; for (int i = 0; i < 100; i++) { int num=rand.nextInt(100); arraylist.add(Integer.valueOf(num)); //get number of >50 if(num>50)total_50++; } System.out.println("numbers of >50 is: "+total_50); //sort the arraylist Comparator<Integer> comp=new MyComparator(); Collections.sort(arraylist, comp); //out min & max System.out.println("Min number is: "+arraylist.get(0)); System.out.println("Max number is: "+arraylist.get(99)); } }
Comparator:
package math; import java.util.Comparator; /** * * @author daniel zhou * */ public class MyComparator implements Comparator<Integer>{ @Override public int compare(final Integer o1, final Integer o2) { final Integer x=(Integer)o1; final Integer y=(Integer)o2; if (x>y) { return 1; }else{ return 0; } } }
或者将比较器写为一个内部类也是可以的,代码如下:
/** * */ package math; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Random; /** * @author daniel zhou * */ public class RandomTest { /** * Create 100 random numbers, get min & max number, sun up the number of >50 * @param args */ public static void main(String[] args) { //create 100 random number ArrayList<Integer> arraylist=new ArrayList<Integer>(); Random rand=new Random(); int total_50=0; for (int i = 0; i < 100; i++) { int num=rand.nextInt(100); arraylist.add(Integer.valueOf(num)); //get number of >50 if(num>50)total_50++; } System.out.println("numbers of >50 is: "+total_50); //sort the arraylist Comparator<Integer> comp=new MyComparator(); Collections.sort(arraylist, comp); //out min & max System.out.println("Min number is: "+arraylist.get(0)); System.out.println("Max number is: "+arraylist.get(99)); } public static class MyComparator implements Comparator<Integer>{ @Override public int compare(final Integer o1, final Integer o2) { final Integer x=(Integer)o1; final Integer y=(Integer)o2; if (x>y) { return 1; }else{ return 0; } } } }