Java每日一题(3)
短信预约 -IT技能 免费直播动态提醒
题目:
使用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;
}
}
}
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;
}
}
}
}
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341