Thinking in Java Fourth Edition Bruce Eckel Chapter 3 Exercise 3

Exercise 3: Modify Exercise 2 so that your code is surrounded by an “infinite” while loop. It will then run until you interrupt it from the keyboard (typically by pressing Control-C).

Solution:

import java.util.*;

public class CompareIntsForever
{
    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)
            {
                System.out.println(x + " < " + y);
            }
            else if(x > y)
            {
                System.out.println(x + " > " + y);
            }
            else
            {
                System.out.println(x + " = " + y);
            }
        }
        Random rand3 = new Random();
        Random rand4 = new Random();
        while(true)
        {
            int x = rand3.nextInt(10);
            int y = rand4.nextInt(10);
            if(x < y)
            {
                System.out.println(x + " < " + y);
            }
            else if(x > y)
            {
                System.out.println(x + " > " + y);
            }
            else
            {
                System.out.println(x + " = " + y);
            }
        }
    }
}

Output:

Leave a Reply

Your email address will not be published. Required fields are marked *