What's the simplest way to print a Java array?
Since Java 5 you can use Arrays.toString(arr)
or Arrays.deepToString(arr)
for arrays within arrays. Note that the Object[]
version calls .toString()
on each object in the array. The output is even decorated in the exact way you're asking.
Examples:
Simple Array:
String[] array = new String[] {"John", "Mary", "Bob"};
System.out.println(Arrays.toString(array));Output:
[John, Mary, Bob]
Nested Array:
String[][] deepArray = new String[][] {{"John", "Mary"}, {"Alice", "Bob"}};
// Gives undesired output:
System.out.println(Arrays.toString(deepArray));
// Gives the desired output:
System.out.println(Arrays.deepToString(deepArray));Output:
[[Ljava.lang.String;@106d69c, [Ljava.lang.String;@52e922]
[[John, Mary], [Alice, Bob]]double
Array:double[] doubleArray = { 7.0, 9.0, 5.0, 1.0, 3.0 };
System.out.println(Arrays.toString(doubleArray));Output:
[7.0, 9.0, 5.0, 1.0, 3.0 ]
int
Array:int[] intArray = { 7, 9, 5, 1, 3 };
System.out.println(Arrays.toString(intArray));Output:
[7, 9, 5, 1, 3 ]
How to print a two dimensional array?
public void printGrid()
{
for(int i = 0; i < 20; i++)
{
for(int j = 0; j < 20; j++)
{
System.out.printf("%5d ", a[i][j]);
}
System.out.println();
}
}
And to replace
public void replaceGrid()
{
for (int i = 0; i < 20; i++)
{
for (int j = 0; j < 20; j++)
{
if (a[i][j] == 1)
a[i][j] = x;
}
}
}
And you can do this all in one go:
public void printAndReplaceGrid()
{
for(int i = 0; i < 20; i++)
{
for(int j = 0; j < 20; j++)
{
if (a[i][j] == 1)
a[i][j] = x;
System.out.printf("%5d ", a[i][j]);
}
System.out.println();
}
}
How to print out the 2D Array in a certain order?
I think this should do it
private static void printArrayEven(int[][] theArray) {
for (int i = 0; i < theArray.length; i++) {
for (int j = 0; j < theArray[i].length; j++) {
if ((theArray[i][j]) % 2 == 0) {
display(theArray[i][j]);
} else {
System.out.print("* ");
}
}
System.out.println();
}
}
System.out.println()
adds a newline at the end of the print statement so you need to use System.out.print()
for the individual characters and print the new line after a row
Pretty print 2D array in Java
If you want something similar to MySQL command-line client output, you can use something like that:
import java.io.PrintStream;
import static java.lang.String.format;
import static java.lang.System.out;
public final class PrettyPrinter {
private static final char BORDER_KNOT = '+';
private static final char HORIZONTAL_BORDER = '-';
private static final char VERTICAL_BORDER = '|';
private static final String DEFAULT_AS_NULL = "(NULL)";
private final PrintStream out;
private final String asNull;
public PrettyPrinter(PrintStream out) {
this(out, DEFAULT_AS_NULL);
}
public PrettyPrinter(PrintStream out, String asNull) {
if ( out == null ) {
throw new IllegalArgumentException("No print stream provided");
}
if ( asNull == null ) {
throw new IllegalArgumentException("No NULL-value placeholder provided");
}
this.out = out;
this.asNull = asNull;
}
public void print(String[][] table) {
if ( table == null ) {
throw new IllegalArgumentException("No tabular data provided");
}
if ( table.length == 0 ) {
return;
}
final int[] widths = new int[getMaxColumns(table)];
adjustColumnWidths(table, widths);
printPreparedTable(table, widths, getHorizontalBorder(widths));
}
private void printPreparedTable(String[][] table, int widths[], String horizontalBorder) {
final int lineLength = horizontalBorder.length();
out.println(horizontalBorder);
for ( final String[] row : table ) {
if ( row != null ) {
out.println(getRow(row, widths, lineLength));
out.println(horizontalBorder);
}
}
}
private String getRow(String[] row, int[] widths, int lineLength) {
final StringBuilder builder = new StringBuilder(lineLength).append(VERTICAL_BORDER);
final int maxWidths = widths.length;
for ( int i = 0; i < maxWidths; i++ ) {
builder.append(padRight(getCellValue(safeGet(row, i, null)), widths[i])).append(VERTICAL_BORDER);
}
return builder.toString();
}
private String getHorizontalBorder(int[] widths) {
final StringBuilder builder = new StringBuilder(256);
builder.append(BORDER_KNOT);
for ( final int w : widths ) {
for ( int i = 0; i < w; i++ ) {
builder.append(HORIZONTAL_BORDER);
}
builder.append(BORDER_KNOT);
}
return builder.toString();
}
private int getMaxColumns(String[][] rows) {
int max = 0;
for ( final String[] row : rows ) {
if ( row != null && row.length > max ) {
max = row.length;
}
}
return max;
}
private void adjustColumnWidths(String[][] rows, int[] widths) {
for ( final String[] row : rows ) {
if ( row != null ) {
for ( int c = 0; c < widths.length; c++ ) {
final String cv = getCellValue(safeGet(row, c, asNull));
final int l = cv.length();
if ( widths[c] < l ) {
widths[c] = l;
}
}
}
}
}
private static String padRight(String s, int n) {
return format("%1$-" + n + "s", s);
}
private static String safeGet(String[] array, int index, String defaultValue) {
return index < array.length ? array[index] : defaultValue;
}
private String getCellValue(Object value) {
return value == null ? asNull : value.toString();
}
}
And use it like that:
final PrettyPrinter printer = new PrettyPrinter(out);
printer.print(new String[][] {
new String[] {"FIRST NAME", "LAST NAME", "DATE OF BIRTH", "NOTES"},
new String[] {"Joe", "Smith", "November 2, 1972"},
null,
new String[] {"John", "Doe", "April 29, 1970", "Big Brother"},
new String[] {"Jack", null, null, "(yes, no last name)"},
});
The code above will produce the following output:
+----------+---------+----------------+-------------------+
|FIRST NAME|LAST NAME|DATE OF BIRTH |NOTES |
+----------+---------+----------------+-------------------+
|Joe |Smith |November 2, 1972|(NULL) |
+----------+---------+----------------+-------------------+
|John |Doe |April 29, 1970 |Big Brother |
+----------+---------+----------------+-------------------+
|Jack |(NULL) |(NULL) |(yes, no last name)|
+----------+---------+----------------+-------------------+
How to print 2D array simplest way with foreach loop?
In 2-dimensional array each element in first loop will be an 1-dimensional array, in second loop each element is a number itself:
int[][] array2d = {{1, 2, 3}, {4, 5, 6}};
for (int[] array : array2d) {
for (int element : array) {
System.out.print(element + " ");
}
System.out.println();
}
Actually, there is a better way using Arrays::toString
library method:
int[][] numbers = {{1, 2, 3}, {4, 5, 6}};
for (int[] array : numbers) {
System.out.println(Arrays.toString(array));
}
How can I print a two-dimensional array of characters in Java, to create a 20x20 grid?
You have to print your 2D array outside outer loop
but you print this 2D array result outside inner loop
. After that you have to remove bracket
and comma
through java replace() method.
Here down is modified code:
import java.util.*;
public class Main
{
public static void main(String[] args) {
final int rows = 20;
final int columns = 20;
String board[][] = new String[rows][columns];
// OUTER LOOP
for (int i = 0; i < rows; i++) {
// INNER LOOP
for (int j = 0; j < columns; j++) {
board[i][j] = ".";
}
}
System.out.print(Arrays.deepToString(board).replace("],", "\n")
.replace(",", "")
.replace("[[", " ")
.replace("[", "")
.replace("]]", ""));
}
}
How to print Two-Dimensional Array like table
public class FormattedTablePrint {
public static void printRow(int[] row) {
for (int i : row) {
System.out.print(i);
System.out.print("\t");
}
System.out.println();
}
public static void main(String[] args) {
int twoDm[][]= new int[7][5];
int i,j,k=1;
for(i=0;i<7;i++) {
for(j=0;j<5;j++) {
twoDm[i][j]=k;
k++;
}
}
for(int[] row : twoDm) {
printRow(row);
}
}
}
Output
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
26 27 28 29 30
31 32 33 34 35
Of course, you might swap the 7 & 5 as mentioned in other answers, to get 7 per row.
How do I print a 2D array filled with 1s and 0s?
Problem
Arrays don't override the toString() method in Java.
If you try printing one directly you will get the className + @ + the hex of the hashCode of the array, as defined by Object.toString();
Solution
Since Java 5 you can use Arrays.toString(arr) or Arrays.deepToString(arr) for arrays within arrays. Note that the Object[] version calls .toString() on each object in the array
So you can easily print your nested array by
System.out.println(Arrays.deepToString(randomArray));
Here the full code
import java.util.*;
public class Whatever {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.print("How many rows? : ");
int numRows = userInput.nextInt(); //numRows works
System.out.print("How many columns? : ");
int numCols = userInput.nextInt(); //numCols works
int randomArray[][] = new int[numRows][numCols];
for (int row = 0; row < randomArray.length; row++) {
int temp = (int) ((Math.random()*2)+1);
for (int col = 0; col < randomArray[row].length; col++) {
if (temp % 2 == 0) randomArray[row][col] = 1;
}
}
System.out.println(Arrays.deepToString(randomArray));
}
}
Related Topics
Why Does Runtime.Exec(String) Work for Some But Not All Commands
Why Should Java 8's Optional Not Be Used in Arguments
Implementing Singleton with an Enum (In Java)
Connecting to Remote Url Which Requires Authentication Using Java
Executorservice, How to Wait for All Tasks to Finish
How to Specify the Java Compiler Version in a Pom.Xml File
How Does Autowiring Work in Spring
How to Write a Custom JSON Deserializer for Gson
How to Tell If I'm Running in 64-Bit Jvm or 32-Bit Jvm (From Within a Program)
How to Use Java Property Files
Java Io Implementation of Unix/Linux "Tail -F"
How to Load a Jar File at Runtime
How to Resolve the "Java.Net.Bindexception: Address Already in Use: Jvm_Bind" Error