日期:2014-05-20 浏览次数:20980 次
import java.util.Random ;
//ps:<<java编程思想(第四版)>>第四章,练习2
//题:写一个程序,产生25个int类型的随机数.对于每一个随机值,使用if-else语句来将其分类为大于、大于,或等于紧随它而随机生成的值.
//书中的答案是错的,这是我的代码,希望能对比我还新的新人有些帮助吧。
public class Demo06
{
public static void main(String args[]){
Random rand=new Random() ;
int x=rand.nextInt() ;
int y=0 ;
for(int i=0;i<24;i++){
if(i==0){
y=rand.nextInt();
if(x>y)System.out.print(x+" > "+y) ;
else if(x<y)System.out.print(x+" < "+y) ;
else System.out.print(x+" = "+y) ;
x=y ;
}else{
y=rand.nextInt();
if(x>y)System.out.print(" > "+y) ;
else if(x<y)System.out.print(" < "+y);
else System.out.print(" = "+y);
x=y ;
}
}
}
}
public class Test {
public static void main(String[] args) {
new Test().random25(0, 1);
}
public void random25(int last,int times) {
Random ran = new Random();
int now = ran.nextInt();
System.out.println(times + ": last=" + last +" now=" + now + " " + compare(last, now));
if(times == 25)
return;
else
random25(now, ++times);
}
private String compare(int i1,int i2) {
if(i1 > i2)
return "大于";
else if(i1 == i2)
return "等于";
else
return "小于";
}
}
------解决方案--------------------
楼主答案错在哪?
------解决方案--------------------
眼睛不好。没看到。。悲剧啊
------解决方案--------------------
这个题好啊。