简体   繁体   中英

While loop with random number generator?

I am new to java coding and while loops are a little confusing to me.

For this program I am asked to generate a random number between 1 and 100, I think I've got that part down.

First the code would print out the random value, and then, if the number is even, it prints out that number of "*" characters, and if its odd, it prints out that number of "&" characters.

I know you could use like modulus to determine odd/even but I don't know how to print out a certain number of characters using the while loop, thanks!

Example output would be:

Random number generated: 8
The output pattern: ********

Random number generated:3
The output pattern: &&&

Generate the number first; test to see if it's even; then print the appropriate strings.

public static void main(String args[]) throws Exception {
    Random rand = new Random();

    int x = rand.nextInt(100) + 1; // nextInt excludes 100, so add 1

    // decide which char to print
    String character = ((x%2) == 0) ? "*" : "&";
    // print
    int i = x;
    while (i > 0) {
        System.out.print(character);
        i--;
    }
}

I have done it with Math.random() function. This code is working....I've tested it my self. Feel free to ask any further doubts😃.

public class random100
{
    public static void main (String args[])
    {
        int rn=0,i=0;
        rn=(int)(Math.random()*100)+1;
        i=rn;
        System.out.println("Random Number="+rn);
        System.out.println("The Output Pattern=");
        if(rn%2==0)
        {
            while(i>0)
            {
                System.out.print("*");
                i--;
            }
        }
        else if(rn%2!=0)
        {
            while(i>0)
            {
                System.out.print("&");
                i--;
            }
        }
    }
}

Here is the screenshot of BlueJ Terminal Window :- Screenshot

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM