Hi...I did some book exercices..i want to ask you are these code right or not?
Question1---Write a programme to display a random choices from a set of 3 choices for breakfast....
i wrote this code...

public class Exercice3_1
{
public static void main(String[] args)
{
    String breakFast = null;
    int choice=0;
    choice = (int)(3*Math.random());

    switch(choice)
    {
        case 1:
        breakFast = "Scrambled";
        System.out.println(breakFast);
        break;

        case 2:
        breakFast = "Sandwitch";
        System.out.println(breakFast);
        break;

        case 3:
        breakFast = "Eggs";
        System.out.println(breakFast);
        break;


    }
}
}

Question-2
A lottery requires that you select six different numbers from the integer 1 tp 49..and generate five sets of entries...
i wrote this code

public class Exercice3_3
{
public static void main(String[] args)
{
    for(int i=0; i<5; i++)
    {
        int number = (int)(49*Math.random());
        System.out.println(number);
    }
}
}

Question-3
Write a programme to generate a random sequence of Capital letters that does not include vowels..
i wrote this code

public class Exercice3_4
{
public static void main(String[] args)
{
    for(int i=65; i<=90; i++)
    {
        char symbol = (char)(i);
        if(!(symbol=='A' || symbol =='E' || symbol=='I' || symbol=='O' || symbol=='U'))
        {
            System.out.println(symbol);
        }
    }
}
}

Kindly tell me all these code are right or not?
Regards...
Farhad

I would recommend you use the Random class in these exercises. Specifically, look at the nextInt(int n) method when you require integers. Calling the default Random() constructor should generate a suitable seed value for your purposes.

For your first question, Math.random() returns values in the range [0,1). This means that the value can be anywhere in the range 0-0.999... but will never equal 1. Given this, choice will only ever be in the range [0,3), which is equivalent to [0,2] when casted to an int.

Your second question has a similar problem to question 1. In addition, the question asks for five sets of six integers. You will require two for-loops to achieve this. Also, the question asks for different (or unique) integers in each set. You could use an array to achieve this.

There is no randomness to your third answer. You need to randomize the values, not simply print a sequential list of them. You'll have to initialize a Random object:

Random random = new Random();

then you can get symbol by calling:

random.nextInt(26) + 65;

Note that the range of nextInt() is 0 (inclusive) to n (exclusive).

Good luck.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.