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?
Related
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 5 years ago.
I am trying to find the max value of a 2D array in java.
import java.util.*;
public class ikiBoyutlu {
public static void ikiBoyut(int[][]a){
int eb= a[0][0];
for(int i=0;i<a.length;i++){
for(int j=0; j<(a[0].length);j++){
if(a[i][j]>eb){
eb=a[i][j];
}
}
}
System.out.println("The max value of array= "+ eb);
}
public static void main(String[] args){
int a[][] ={{2,5,7,0,-6,28,43},{-96,45,3,21}};
ikiBoyut(a);
}
}
But I get index out of range error. I wonder why?
Thanks!
You're iterating over different nested arrays, while invariably watching i < a[0].
Your inner loop should be declared this way, instead:
for(int j=0; j<(a[i].length);j++)
and in your example the second inner array is smaller than the first. so when iterating through the second with the length of the first, it will definitely get out of the bounds ...
You have a two dimensional array, which is basically an array of arrays.
Your two two dimensional array effectively contains two arrays with different lengths.
Your second loop has the condition of
j<(a[0].length)
when it should be
j<(a[i].length)
Use the length of each array element.
You are testing the inner loop against a[0].length which is the length of the first array in your jagged multidimensional array (and longer than the second). Instead, use a[i].length - and you might also initialize eb with Integer.MIN_VALUE and use Math.max(int, int) instead of coding your own test. Like,
public static void ikiBoyut(int[][] a) {
int eb = Integer.MIN_VALUE;
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
eb = Math.max(eb, a[i][j]);
}
}
System.out.println("The max value of array= " + eb);
}
This is also a place where you could potentially eliminate errors by using a for-each loop. For example,
public static void ikiBoyut(int[][] a) {
int eb = Integer.MIN_VALUE;
for (int[] arr : a) {
for (int i : arr) {
eb = Math.max(eb, i);
}
}
System.out.println("The max value of array= " + eb);
}
And, in Java 8+, we can use lambdas to shorten it significantly. Like,
public static void ikiBoyut(int[][] a) {
int eb = Stream.of(a).flatMapToInt(IntStream::of).max().orElse(Integer.MIN_VALUE);
System.out.println("The max value of array= " + eb);
}
This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 6 years ago.
So I have an array and trying to print what was input to the scanner. I'm trying to print the matrix that was input. Heres the code, what am I doing wrong here? I tried to print just graph, doesn't work.
/** Accept number of vertices **/
System.out.println("Enter number of vertices\n");
int V = input.nextInt();
/** get graph **/
System.out.println("\nEnter matrix\n");
int[][] graph = new int[V][V];
for (int i = 0; i < V; i++)
for (int j = 0; j < V; j++)
graph[i][j] = input.nextInt();
System.out.print(graph);
Printing arrays by simply passing it into System.out.print will print the array's hashcode. See this.
What you want to do is: System.out.println(Arrays.deepToString(graph));
Arrays.toString(...) will work for single dimensional arrays.
Arrays.deepToString(...) will work for more complex arrays.
Because when you try to print graph, you are actually printing a reference to an array object (If I am correct).
Also, for variables (like "V") you should use small caps
Instead of printing a graph, do this:
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
System.out.print(graph[i][j]);
}
System.out.println();
}
You can print the contents of an array using the Arrays.toString() method but it doesn't work for multidimensional arrays, so for a 2 dimensional array, you'll need to loop through the elements in the first dimension. Like this:
for (int[] g : graph) {
System.out.println(Arrays.toString(g));
}
This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 6 years ago.
I want to shift elements in an array to the right by 1. The last element should go to position 0. So far, I only have the shifting to the right part done, I want to see if this is the right but when I press run, nothing shows up in the console. I know I have to put System.out.println(); in the main but I don't know what to call with the print command. Here is my code.
I tried putting in System.out.println(rotate({1,2,3,4})); into main but I get an error...
public class Rotate {
static void rotate(int[] A) {
int arrayLength = A.length;
for(int i = 0; i <= arrayLength-1; i++){
A[i] = A[i+1];
}
}
public static void main(String[] args){
}
}
You need to make a call to a function that can print, for example System.out.println(). Now there are some other issues with your code and you'll need to make some changes (there is more than one way to do this). One way would be to return an array from your rotate function, and then print the arrays that is returned.
static int[] rotate(int[] A) {
int arrayLength = A.length;
for(int i = 0; i <= arrayLength-1; i++){
A[i] = A[i+1];
}
return A;
}
We can call this now from our main method, and print each element. If you just call the System.out.println()method and pass it an array, it will print the Hashcodefor this object. This is not that usefull for printing information of an array. So instead, you can write a loop and print each element in the array.
public static void main (String[] args)
{
int[] x = {1,2,3,4};
int[] y = (rotate(x));
System.out.println(y) // prints the hash, not what you want..
for(int i = 0; i < y.length(); i++){
System.out.println(y[i]);
}
}
Instead of printing each element of the array seperately, you could also print the entire array using System.out.println(Arrays.toString(y));.
You'll still get an error now
This is because your rotate method is not implemented correctly. But that is beyond the scope of this question I suppose.
To verify that this is actually working, you could try to print the array before applying rotateto it.
int[] x = {1,2,3,4};
for(int i = 0; i < x.length; i++) {
System.out.println(x[i]);
}
// or alternative
System.out.println(Arrays.toString(x));
To solve rotate and print problem (and if you don't want to return array):
static void rotate(int[] A) {
int arrayLength = A.length;
int t = A[arrayLength-1];
for (int i = arrayLength - 1; i > 0; i--) {
A[i] = A[i-1];
}
A[0] = t;
for (int i : A) {
System.out.println(i);
}
}
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();
}
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