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

解决方案 »

  1.   

    import java.util.Random;
    没有这句引入,不能执行吧
      

  2.   

    这个是书里的答案。// control/CompareInts.java
    // TIJ4 Chapter Control, Exercise 2, page 139
    /* Write a program that generates 25 random int values. For each value, use an
    * if-else statement to classify it as greater than, less than or equal to a
    * second randomly generated value.
    */import static net.mindview.util.Print.*;
    import java.util.*;public class CompareInts {
    public static void main(String[] args) {
    Random rand1 = new Random();
    Random rand2 = new Random();
    for(int i = 0; i < 25; i++) {
    int x = rand1.nextInt();
    int y = rand2.nextInt();
    if(x < y) print(x + " < " + y);
    else if(x > y) print(x + " > " + y);
    else print(x + " = " + y);
    }
    Random rand3 = new Random();
    Random rand4 = new Random();
    for(int i = 0; i < 25; i++) {
    int x = rand3.nextInt(10);
    int y = rand4.nextInt(10);
    if(x < y) print(x + " < " + y);
    else if(x > y) print(x + " > " + y);
    else print(x + " = " + y);
    }
    }
    }
      

  3.   


    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 "小于";
    }
    }
    :)
      

  4.   

    为什么还要在for循环里判断i是否等于0的情况?
    只需要这样写就完了,我觉得是符合题意的~!import java.util.*;
    import static net.mindview.util.Print.*;public class CompareInts {
        public static void main(String[] args) {
        // Create a seeded random number generator:
        Random rand = new Random();
        int j = rand.nextInt(100);
        for(int i = 0;  i< 24; i++){
            int k = rand.nextInt(100);
            if(j < k)print(j +"<"+ k); 
                else if(j == k)print(j +"="+ k); 
                    else print(j +">"+ k); 
            j = k;
            }
        }