The best way to print a Java 2D array? [closed] - java

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
I was wondering what the best way of printing a 2D array in Java was?
I was just wondering if this code is good practice or not?
Also any other mistakes I made in this code if you find any.
int rows = 5;
int columns = 3;
int[][] array = new int[rows][columns];
for (int i = 0; i<rows; i++)
for (int j = 0; j<columns; j++)
array[i][j] = 0;
for (int i = 0; i<rows; i++) {
for (int j = 0; j<columns; j++) {
System.out.print(array[i][j]);
}
System.out.println();
}

You can print in simple way.
Use below to print 2D array
int[][] array = new int[rows][columns];
System.out.println(Arrays.deepToString(array));
Use below to print 1D array
int[] array = new int[size];
System.out.println(Arrays.toString(array));

I would prefer generally foreach when I don't need making arithmetic operations with their indices.
for (int[] x : array)
{
for (int y : x)
{
System.out.print(y + " ");
}
System.out.println();
}

Simple and clean way to print a 2D array.
System.out.println(Arrays.deepToString(array).replace("], ", "]\n").replace("[[", "[").replace("]]", "]"));

There is nothing wrong with what you have. Double-nested for loops should be easily digested by anyone reading your code.
That said, the following formulation is denser and more idiomatic java. I'd suggest poking around some of the static utility classes like Arrays and Collections sooner than later. Tons of boilerplate can be shaved off by their efficient use.
for (int[] row : array)
{
Arrays.fill(row, 0);
System.out.println(Arrays.toString(row));
}

Two-liner with new line:
for(int[] x: matrix)
System.out.println(Arrays.toString(x));
One liner without new line:
System.out.println(Arrays.deepToString(matrix));

That's the best I guess:
for (int[] row : matrix){
System.out.println(Arrays.toString(row));
}

From Oracle Offical Java 8 Doc:
public static String deepToString(Object[] a)
Returns a string representation of the "deep contents" of the
specified array. If the array contains other arrays as elements, the
string representation contains their contents and so on. This method
is designed for converting multidimensional arrays to strings.

|1 2 3|
|4 5 6|
Use the code below to print the values.
System.out.println(Arrays.deepToString());
Output will look like this (the whole matrix in one line):
[[1,2,3],[4,5,6]]

With Java 8 using Streams and ForEach:
Arrays.stream(array).forEach((i) -> {
Arrays.stream(i).forEach((j) -> System.out.print(j + " "));
System.out.println();
});
The first forEach acts as outer loop while the next as inner loop

System.out.println(Arrays.deepToString(array)
.replace("],","\n").replace(",","\t| ")
.replaceAll("[\\[\\]]", " "));
You can remove unwanted brackets with .replace(), after .deepToString if you like.
That will look like:
1 | 2 | 3
4 | 5 | 6
7 | 8 | 9
10 | 11 | 12
13 | 15 | 15

#Ashika's answer works fantastically if you want (0,0) to be represented in the top, left corner, per standard matrix convention. If however you would prefer to put (0,0) in the lower left hand corner, in the style of the standard coordinate system, you could use this:
LinkedList<String> printList = new LinkedList<String>();
for (char[] row: array) {
printList.addFirst(Arrays.toString(row));;
}
while (!printList.isEmpty())
System.out.println(printList.removeFirst());
This used LIFO (Last In First Out) to reverse the order at print time.

Try this,
for (char[] temp : box) {
System.err.println(Arrays.toString(temp).replaceAll(",", " ").replaceAll("\\[|\\]", ""));
}

Adapting from https://stackoverflow.com/a/49428678/1527469 (to add indexes):
System.out.print(" ");
for (int row = 0; row < array[0].length; row++) {
System.out.print("\t" + row );
}
System.out.println();
for (int row = 0; row < array.length; row++) {
for (int col = 0; col < array[row].length; col++) {
if (col < 1) {
System.out.print(row);
System.out.print("\t" + array[row][col]);
} else {
System.out.print("\t" + array[row][col]);
}
}
System.out.println();
}

class MultidimensionalArray {
public static void main(String[] args) {
// create a 2d array
int[][] a = {
{1, -2, 3},
{-4, -5, 6, 9},
{7},
};
// first for...each loop access the individual array
// inside the 2d array
for (int[] innerArray: a) {
// second for...each loop access each element inside the row
for(int data: innerArray) {
System.out.println(data);
}
}
}
}
You can do it like this for 2D array

Related

How to print an 2d array of Char (JAVA) [duplicate]

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 4 years ago.
I am trying to print out a gameBoard that has a "-" for each spot of the array: however every time I run this code I get this printed to the console:
[[C#2a139a55.
Any suggestions?
public class Game {
public static void main(String[] args){
char realBoard[][] = new char[7][7];
for (int i=0;i<7;i++){
for(int j=0;j<7;j++){
realBoard[i][j]='-';
}
}
System.out.print((realBoard));
}
}
realBoard is an array, an object, so you can't just print it like that. You will need to iterate over the elements again
for(char[] y: realBoard) {
for(char x: realBoard) {
System.out.print(x);
}
System.out.println();
}
Unless you need to use the array data of mark elsewhere, you would be better off just using print statements inside your loops.
for(int i = 0; i < 7; i++) {
for(int j = 0; j < 7; j++) {
//Print for each row
System.out.print("-");
}
//Move to next line
System.out.print("\n");
}
You can't print a 2D array like that. To print a 2D array in one line you can use:
System.out.println(Arrays.deepToString(realBoard));
Or in multiple lines:
for(char[] x: realBoard)
System.out.println(Arrays.toString(x));
Credits: Java - Best way to print 2D array?

Can't access the values of nested list elements, Java 8

First of all, I easily got this to work with the regular way of populating and accessing data from an array, so that as a suggested solution isn't what I'm looking for. I'm trying to better understand how to populate and access data from a multi-dimensional array. When I run the program the NetBeans error message is: cannot find symbol, symbol: method get(int), location: class Integer. I've looked at the .get() method for ArrayList and to me it seems like I'm correctly trying to access that data but something isn't right. Also, on the last statement of the program code NetBeans says incompatible types: ArrayList<Integer> cannot be converted to Object[]. I'm guessing that's because when I'm trying print the values of each nested element each value wants to be accessed as a String, it's just a guess.
So the the array I want to populate should look like this: [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]], and output should look something like below.
1 2 3 4
5 6 7 8
9 10 11 12
// TwoDimensionalArray_v2.java
// demonstrates populating and accessing elements from a two-dimensional array
package twodimensionalarray_v2;
import java.util.*;
public class TwoDimensionalArray_v2 {
public static void main(String args[]) {
// declare a dynamic array of class type Integer
ArrayList<Integer> table = new ArrayList<>();
// loop variables
int i, j;
// populate the array one nested element at a time
for (i = 0; i < 3; ++i) {
for (j = 0; j < 4; ++j) {
table.set(i, (i * 4) + j + 1);
// >>>>> NetBeans error message is for the below line on .get(j) <<<<<
System.out.print(table.get(i).get(j) + " ");
}
System.out.println();
}
// print 'table'
System.out.println();
System.out.println(Arrays.deepToString(table));
}
}
A list is a one-dimensional structure but you can use any aggregate for elements. Another List as element results in a two-dimensional array.
List<List<Integer>> table = new ArrayList<>();
// populate the array one nested element at a time
for (int i = 0; i < 3; ++i) {
List<Integer> row;
table.add( row = new ArrayList<Integer>() );
for (int j = 0; j < 4; ++j) {
row.add( (i * 4) + j + 1);
}
}
for (int i = 0; i < table.size(); ++i) {
for (int j = 0; j < table.get(i).size(); ++j) {
System.out.print( " " + table.get(i).get(j));
}
System.out.println();
}
You could do the same using proper arrays.
your table is Arraylist ,
table.get(i)
will give you integer value that you had set at particulate position, as you are setting integer in array with line:
table.set(i, (i * 4) + j + 1);
so get(i) gives you integer value only not a array or list
Yep. sorry.
You cannot access get(j) because the List is just a list (one dimension).
You should use an primitive Array[][]

Reprint a String array Java

I have a string array
"Ben", "Jim", "Ken"
how can I print the above array 3 times to look like this:
"Ben", "Jim", "Ken"
"Jim", "Ben", "Ken"
"Ken", "Jim", "Ben"
I just want each item in the initial array to appear as the first element. The order the other items appear does not matter.
more examples
Input
"a","b","c","d"
output
"a","b","c","d"
"b","a","c","d"
"c","b","a","d"
"d","a","c","d"
Method signature
public void printArray(String[] s){
}
Rather than give you straight-up code, I'm going to try and explain the theory/mathematics for this problem.
The two easiest ways I can come up with to solve this problem is to either
Cycle through all the elements
Pick an element and list the rest
The first method would require you to iterate through the indices and then iterate through all the elements in the array and loop back to the beginning when necessary, terminating when you return to the original element.
The second method would require you to iterate through the indices, print original element, then proceed to iterate through the array from the beginning, skipping the original element.
As you can see, both these methods require two loops (as you are iterating through the array twice)
In pseudo code, the first method could be written as:
for (i = array_start; i < array_end; i++) {
print array_element[i]
for (j = i + 1; j != i; j++) {
if (j is_larger_than array_end) {
set j equal to array_start
}
print array_element[j]
}
}
In pseudo code, the second method could be written as:
for (i = array_start; i < array_end; i++) {
print array_element[i]
for (j = array_start; j < array_end; j++) {
if (j is_not_equal_to i) {
print array_element[j]
}
}
}
public void printArray(String[] s){
for (int i = 0; i < s.length; i++) {
System.out.print("\"" + s[i] + "\",");
for (int j = 0; j < s.length; j++) {
if (j != i) {
System.out.print("\"" + s[j] + "\",");
}
}
System.out.println();
}
}
This sounds like a homework question so while I feel I shouldn't answer it, I'll give a simple hint. You are looking for an algorithm which will give all permutations (combinations) of the "for loop index" of the elements not the elements themselves. so if you have three elements a,b,c them the index is 0,1,2 and all we need is a way to generate permutations of 0,1,2 so this leads to a common math problem with a very simple math formula.
See here: https://cbpowell.wordpress.com/2009/11/14/permutations-vs-combinations-how-to-calculate-arrangements/
for(int i=0;i<s.length;i++){
for(int j=i;j<s.length+i;j++) {
System.out.print(s[j%(s.length)]);
}
System.out.println();
}
Using mod is approppiate for this question. The indexes of the printed values for your first example are like this;
0 1 2
1 2 0
2 0 1
so if you write them like the following and take mod of length of the array (3 in this case) you will reach solution.
0 1 2
1 2 3
2 3 4

Filling 2d array

Okay probably it's a very easy solution, but I can't seem to find it. I've got two ArrayLists:
ArrayList<Candidate>partyList and ArrayList<Party>electoralList
Now I want to make a 2d int array that represents the parties and candidates like this:
p c
1 1
1 2
1 3
2 1
2 2
3 1
3 2
3 3
etc.
I think I already have the right for-loop to fill the array but I only miss the correct formula to do it.
int[][]ArrList;
for (int i=0; i<parties.size(); i++){
for(int j=0; j<parties.get(i).getPartyList().size(); j++){
ArrList[i][j]=
Is the for-loop indeed correct? And what is the formula to fill the array then?
I will try and answer the question from how I understood what you are looking for here.
You should understand this first:
A 2D array consists of a nestled array i.e. ArrList[2][3] = [ [1,2,3], [1,2,3] ] -> The first digit declares How many arrays as elements, the second digit declares Size or if you like: length, of the array elements
If you are looking for to represent the candidates and parties as numbers. Here is my solution:
int[][]ArrList = new int[parties.size()][electoral.size()]
for (int depth=0; depth < parties.size(); depth++){
for(int itemIndex=0; itemIndex<parties.get(depth).getPartyList().size(); itemIndex++){
ArrList[depth][itemIndex]= itemIndex;
I hope this is what you were looking for.
First of all, ArrList should not have a starting capital letter (it is not a class but an object).
Second point (I think what troubles you) is that you are not initializing the matrix and the parties.size() are always 0. I am not sure since there is not enough code though.
You could do something like this
int ROWS = 10;
int COLS = 2;
int [][] matrix = new int[ROWS][];
for(int i=0; i< matrix.length; i++){
matrix[i] = new int[COLS];
}
or, with lists
int ROWS = 10;
int COLS = 2;
List<List<Object>> matrix = new ArrayList<>(ROWS);
for (int i = 0; i < ROWS; i++) {
ArrayList<Object> row = new ArrayList<>(COLS);
for (int j = 0; j < COLS; j++) {
row.add(new Object());
}
matrix.add(row);
}
int[][] arrList=new int[parties.size()][2];
int i=0,j=0,k=0;
for(;i<parties.size();i++,j++){
if(j==1){
arrList[k][j]=electoralList .get(--i);
j=-1;
k++;
}
else{
arrList[k][j]=parties.get(i);
}
}
arrList[k][j]=aarM.get(electoralList .size()-1);
System.out.println(Arrays.deepToString(arrList));

Java - Printing 2d array with (with spaces between lines) [duplicate]

This question already has answers here:
The best way to print a Java 2D array? [closed]
(14 answers)
Closed 7 years ago.
I have a basic java question - I have an array and I need to do a multiplication of all the elements, so for input:
1 2 3
The output will be:
1 2 3
2 4 8
3 6 9
How can I print the 2d array from the main ?
PS - I want the method just to return the new 2d array, without printing it ( I know I can do it without the method and and print mat[i][j] within the nested loop)
public class Main {
public static void main(String[] args) {
int[] array = {1, 2, 3};
System.out.println(matrix(array));
}
public static int[][] matrix(int[] array){
int[][] mat = new int[array.length][array.length];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
mat[i][j] = array[i] * array[j];
}
}
return mat;
}
}
You have to print all the individual elements of the array, because if you just try to print an array, it will print all kinds of other stuff you might not want to see. So you cherry pick out what you want, and format it a little. In the below code you have each element printed, seperated on a space until it reaches a new row, where it then jumps to a new line.
int[][] matrixArray = matrix(array);
for(int i = 0, i < matrixArray.length; i++) {
for(int j = 0; j < matrixArray[0].length; j++) {
System.out.print(matrixArray[i][j] + " ");
}
System.out.println();
}

Categories

Resources