Phenom588
Phenom588

Reputation: 81

Using random and decimal format together

I am trying to create a random four digit number and then use decimal format to print it out as (# * 1000) + (# * 100) + (# * 10) + (# * 1). For example, say i generate 7956 it would take that, split it up and print out as (7 * 1000) + (9 * 100) + (5 * 10) + (6 * 1). So far this is what I have:

public static void main(String [] args)
{
    Random random = new Random();
    int number = random.nextInt(10000);


    DecimalFormat formatOne;
    formatOne = new DecimalFormat("(# * 1000) + (# * 100) + (# * 10) + (# * 1)");

    System.out.println("The random number was: " + number);
    System.out.println("Which is: " + formatOne.format( random.nextInt(10000) ) );


}

I was thinking I'd be able to use just that format, but since 0 is any number including zero it won't print it out correctly. I've tried splitting it up, but it ends up just taking the zeros from the number i'm multiplying by and putting them on the end of the first number. I am in a fairly low level java class, and haven't even gotten to loops yet so if you could keep this as simple as possible it would be greatly appreciated. Thank you for any and all help!

Upvotes: 1

Views: 272

Answers (1)

Bohemian
Bohemian

Reputation: 425073

DecimalFormat doesn't work that way.

You'll have to do it in code.

You might consider getting the number as a String, then iterating backwards (last to first) over its characters in a loop that builds up the output you want.

Upvotes: 4

Related Questions