简体   繁体   中英

Java: Generating a random 3 digit number using a for loop

I need to generate a random 3 digit number using a for loop for a project but am completely stuck. Here is what i have.

    for(int counter = 0; counter < 3; counter++){
        randNum = r.nextInt(9 - 9 + 1) + 9;
        System.out.println(singleNum1);
    }

I know how to generally use a for loop, just not for generating a number. And each number has to be seperated, and then pieced together. How would i go about doing this?

You can do this differently but the main message here is to check out the methods you're using and the way they are working before starting coding with them.

If the use of methods is complicated, use simple algorithms and then try optimizing them.

Here is a method :

    Random r = new Random();
    String output = "";
    for (int i = 0 ; i < 3 ; i++){
        output+=r.nextInt(10);
    }
    int outputInt = Integer.parseInt(output);

Here is a second one :

    Random r = new Random();
    int output = 0;
    for (int i = 0 ; i < 3 ; i++){
        output+=(r.nextInt(10)*Math.pow(10, i));
    }
    System.out.println(output);

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