Java每日一题(3)

2023-01-31 01:01:56 java 每日
题目:
使用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;


public class RandomTest {

  
  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));
    
  }
    
}

 
Comparator:
package math;

import java.util.Comparator;

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;


public class RandomTest {

  
  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;
      }
    }
    
  }
}

 

相关文章