I want to print several arrays and the element of output will with field width 3 , I think I can use printf
, but if I use printf
then I need to write the format of all element of array , but the array is big .
for example
@array = (1,10,100,30);
printf ("%3d %3d %3d %3d\n",$array[0],$array[1],$array[2],$array[3]);
I know I can use loop to print a element until all the array loop through , but I think it's not a good idea .
Does there exists any way can let me just describe the format of element one time , then apply to the whole array automatically?
something like this?
printf ("%3d\n",@array);
thanks
Print an Array Using Arrays. toString() and Arrays. deepToString() The built-in toString() method is an extremely simple way to print out formatted versions of objects in Java.
We cannot print array elements directly in Java, you need to use Arrays. toString() or Arrays. deepToString() to print array elements. Use toString() method if you want to print a one-dimensional array and use deepToString() method if you want to print a two-dimensional or 3-dimensional array etc.
Here are two approaches:
Use a loop
printf "%3d ", $_ for @array;
print "\n";
Use the x
operator to build a variable length template
printf "%3d " x @array . "\n", @array;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With