Reece
Reece

Reputation: 35

Java - Format double array

I have created a loop below that will display around 50 numbers 'at random' between 1 & 999. The problem I have is that I need to print out the entire array outside the loop (as attempted) but I need it in the same format I have printed it within the loop.

I have tried a few ways of doing it, but it keeps throwing errors, mainly to do with 'illegal conversions'.

// Imports
import java.util.Arrays;
import java.text.DecimalFormat;

// Class
public class Random50
{
  public static void main(String[] args)
  {
    // Declaration
    double[] Random50Array = new double[51];
    DecimalFormat df = new DecimalFormat("000");
    int i;

    // Loops
    for(i = 0; i < Random50Array.length; i++)
    {
      Random50Array[i] = (int)(Math.random() * 999);
      System.out.print(df.format(Random50Array[i]) + ", ");
    }
    System.out.println("");
    System.out.println("");
    String RandomArray = (Arrays.toString(Random50Array));
    System.out.printf("%03d", RandomArray);
  }
 }

I appreciate any future guidance given. :)

Upvotes: 1

Views: 2508

Answers (2)

UVM
UVM

Reputation: 9914

Optimized Code: You do not need double array, don't you

 StringBuilder builder = new StringBuilder();
for(i = 0; i < Random50Array.length; i++)
{
  String output = df.format((int)(Math.random()*999)+ ", ";
  builder.append(output);
}

System.out.println("");
System.out.println("");
System.out.print(builder.toString());

Upvotes: 0

Andrew Sun
Andrew Sun

Reputation: 4231

You could append the formatted strings within the loop together, and print them out all at once at the end.

// ...
StringBuilder builder = new StringBuilder();
for(i = 0; i < Random50Array.length; i++)
{
  Random50Array[i] = (int)(Math.random()*999);
  String output = df.format(Random50Array[i])+ ", ";
  System.out.print(output);
  builder.append(output);
}

System.out.println("");
System.out.println("");
System.out.print(builder.toString());

Note that you shouldn't use System.out.printf("%03d", "..."); to print strings, since the "%03d" means that the argument you are passing is a number. This is the cause of the errors you are experiencing.

Upvotes: 2

Related Questions