Home > java > Why won't this print the user-inputted array in reverse?

Why won't this print the user-inputted array in reverse?

January 3Hits:2
Advertisement

In Java, arrays don't override toString(), so if you try to print one directly, you get weird output including the memory location:

int[] intArray = new int[] {1, 2, 3, 4, 5}; System.out.println(intArray);     // prints something like '[[email protected]' 

But usually we'd actually want something more like [1, 2, 3, 4, 5]. What's the simplest way of doing that? Here are some example inputs and outputs:

// array of primitives: int[] intArray = new int[] {1, 2, 3, 4, 5}; //output: [1, 2, 3, 4, 5]  // array of object references: String[] strArray = new String[] {"John", "Mary", "Bob"}; //output: [John, Mary, Bob] 

Answers

In Java 5 Arrays.toString(arr) or Arrays.deepToString(arr) for arrays within arrays. Note that Object[] version calls .toString() of each object in array. If my memory serves me correct, the output is even decorated in the exact way you're asking.

Edit: Don't forget to add import java.util.Arrays; like this:

package packageName;
import java.util.Arrays;
...

Example

// 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"}};
System.out.println(Arrays.toString(deepArray));
//output: [[Ljava.lang.String;@106d69c, [Ljava.lang.String;@52e922]
System.out.println(Arrays.deepToString(deepArray));
//output: [[John, Mary], [Alice, Bob]]

//double Array
double[] arrayGiven = { 7.0, 9.0, 5.0, 1.0, 3.0 };
System.out.println(Arrays.toString(arrayGiven));
// Output [7.0, 9.0, 5.0, 1.0, 3.0 ]

//int Array
int[] arrayInt = { 7, 9, 5, 1, 3 };
System.out.println(Arrays.toString(arrayInt));
// Output [7, 9, 5, 1, 3 ]

Always check the standard libraries first. Try:

System.out.println(Arrays.toString(array));

or if your array contains other arrays as elements:

System.out.println(Arrays.deepToString(array));

This is nice to know, however, as for "always check the standard libraries first" I'd never have stumbled upon the trick of Arrays.toString( myarray )

--since I was concentrating on the type of myarray to see how to do this. I didn't want to have to iterate through the thing: I wanted an easy call to make it come out similar to what I see in the Eclipse debugger and myarray.toString() just wasn't doing it.

import java.util.Arrays;
.
.
.
System.out.println( Arrays.toString( myarray ) );

In JDK1.8 you can use aggregate operations and a lambda expression:

String[] strArray = new String[] {"John", "Mary", "Bob"};

Arrays.asList(strArray).stream().forEach(s -> System.out.println(s));

/* output:
John
Mary
Bob
*/

If you're using Java 1.4, you can instead do:

System.out.println(Arrays.asList(array));

(This works in 1.5+ too, of course.)

Arrays.deepToString(arr) only prints on one line.

int[][] table = new int[2][2];

To actually get a table to print as a two dimensional table, I had to do this:

System.out.println(Arrays.deepToString(table).replaceAll("],", "]," + System.getProperty("line.separator")));

It seems like the Arrays.deepToString(arr) method should take a separator string, but unfortunately it doesn't.

for(int n: someArray) {
    System.out.println(n+" ");
}

Using regular for loop is the simplest way of printing array in my opinion. Here you have a sample code based on your intArray

for (int i = 0; i < intArray.length; i++) {
   System.out.print(intArray[i] + ", ");
}

It gives output as yours 1, 2, 3, 4, 5

Prior to Java 8 we could have used Arrays.toString(array) to print one dimensional array and Arrays.deepToString(array) for multi-dimensional arrays. We have got the option of Stream and lambda in Java 8 which can also be used for the printing the array.

Printing One dimensional Array:

public static void main(String[] args) {
    int[] intArray = new int[] {1, 2, 3, 4, 5};
    String[] strArray = new String[] {"John", "Mary", "Bob"};

    //Prior to Java 8
    System.out.println(Arrays.toString(intArray));
    System.out.println(Arrays.toString(strArray));

    // In Java 8 we have lambda expressions
    Arrays.stream(intArray).forEach(System.out::println);
    Arrays.stream(strArray).forEach(System.out::println);
}

The output is:

[1, 2, 3, 4, 5]
[John, Mary, Bob]
1
2
3
4
5
John
Mary
Bob

Printing Multi-dimensional Array Just in case we want to print multi-dimensional array we can use Arrays.deepToString(array) as:

public static void main(String[] args) {
    int[][] int2DArray = new int[][] { {11, 12}, { 21, 22}, {31, 32, 33} };
    String[][] str2DArray = new String[][]{ {"John", "Bravo"} , {"Mary", "Lee"}, {"Bob", "Johnson"} };

    //Prior to Java 8
    System.out.println(Arrays.deepToString(int2DArray));
    System.out.println(Arrays.deepToString(str2DArray));

    // In Java 8 we have lambda expressions
    Arrays.stream(int2DArray).flatMapToInt(x -> Arrays.stream(x)).forEach(System.out::println);
    Arrays.stream(str2DArray).flatMap(x -> Arrays.stream(x)).forEach(System.out::println);
}

Now the point to observe is that the method Arrays.stream(T[]), which in case of int[] returns us Stream<int[]> and then method flatMapToInt() maps each element of stream with the contents of a mapped stream produced by applying the provided mapping function to each element.

The output is:

[[11, 12], [21, 22], [31, 32, 33]]
[[John, Bravo], [Mary, Lee], [Bob, Johnson]]
11
12
21
22
31
32
33
John
Bravo
Mary
Lee
Bob
Johnson

Starting with Java 8, one could also take advantage of the join() method provided by the String class to print out array elements, without the brackets, and separated by a delimiter of choice (which is the space character for the example shown below):

String[] greeting = {"Hey", "there", "amigo!"};
String delimiter = " ";
String.join(delimiter, greeting)

The output will be "Hey there amigo!".

A simplified shortcut I've tried is this:

    int x[] = {1,2,3};
    String printableText = Arrays.toString(x).replaceAll("[\\[\\]]", "").replaceAll(", ", "\n");
    System.out.println(printableText);

It will print

1
2
3

No loops required in this approach and it is best for small arrays only

There's one additional way if your array is of type char[]:

char A[] = {'a', 'b', 'c'}; 

System.out.println(A); // no other arguments

prints

abc

public class printer {

    public static void main(String[] args) {
        String a[] = new String[4];
        Scanner sc = new Scanner(System.in);
        System.out.println("enter the data");
        for (int i = 0; i < 4; i++) {
            a[i] = sc.nextLine();
        }
        System.out.println("the entered data is");
        for (String i : a) {
            System.out.println(i);
        }
      }
    }

Using org.apache.commons.lang3.StringUtils.join(*) methods can be an option
For example:

String[] strArray = new String[] { "John", "Mary", "Bob" };
String arrayAsCSV = StringUtils.join(strArray, " , ");
System.out.printf("[%s]", arrayAsCSV);
//output: [John , Mary , Bob]

I used the following dependency

<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.3.2</version>

To add to all the answers, printing the object as a JSON string is also an option.

Using Jackson:

ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
System.out.println(ow.writeValueAsString(anyArray));

Using Gson:

Gson gson = new Gson();
System.out.println(gson.toJson(anyArray));

The simplest way to print an array is to use a for-loop:

// initialize array
for(int i=0;i<10;i++)
{
    System.out.print(array[i] + " ");
}

Related Articles

  • Why won't this print the user-inputted array in reverse? January 3

    In Java, arrays don't override toString(), so if you try to print one directly, you get weird output including the memory location: int[] intArray = new int[] {1, 2, 3, 4, 5}; System.out.println(intArray); // prints something like '[[email protected]' But u

  • 'ValueError: could not broadcast input array from shape (0,0) into shape (1,1)' when using sm.tsa.SARIMAXJanuary 14

    I am trying to use the statsmodels.api.tsa.SARIMAX function to model some 30 minute frequency time series data but am getting the error below. The SARIMAX function is not included in the latest released version of statsmodels, so I have downloaded an

  • How can i print a list of arrays in JAVA?February 10

    i'm trying to write a program in java to print a list of arrays. I know there's already Array.toString(arr) method, but i don't want the "[..]" on the list. I wrote some simple code to do so. public static void main(String[] args){ Scanner in =

  • Print elements of an array in batch scriptDecember 1

    I'm trying to print elements of an array in batch script: for %%i in (*.txt) do ( echo !array[%n1%]! set /A n1+=1 ) But it does not print the array elements. It prints the same thing again and again. I have also tried !array[!n1!]! but it does not wo

  • \input in the reverse order

    \input in the reverse orderApril 21

    I wonder if there is a reverse version of input. For instance, I maintenance a list of things. list.txt \myitem{20080103}{a} \myitem{20090202}{b} I could do \input{list.txt} and define \myitem in one file to generate an itemized list. But now I want

  • Expectations on input / output of array dimensions and approaches to implement support for variable dimensions input arraysMarch 1

    Preamble As we are vectorising our colour API, we are changing the accepted input types for most of our functions. We would be keen on keeping backward compatibility with the existing code. Let's define the following input variables: numeric R shape:

  • A C++ library for configurable pretty-printing/dumping of large arrays?November 21

    I am looking for a library - or a piece-of-a-library - for printing the contents of arrays of elements of simple types to an output stream. Its basic use is debugging code which processes very large vectors (of ints, floats, doubles, chars) - I want

  • XslCompiledTransform.Transform: pass a list of strings as input parameter and check "input array contains"January 17

    How to pass a list of strings in XslCompiledTransform.Transform method and check inside xsl document condition like "input array contains some attribute of xml node"? I know that I can pass a string but how to parse it? What if I want to pass 10

  • jquery not updating sum of input array after clone append removeFebruary 6

    I have a multiple user yearly membership form where many users can register at one time with two controls as + Add or - Remove with jQuery clone function. The summing function works perfectly on a normal non jQuery form on input array with same name

  • Printing a multi dimensional array using one Foreach loop onlyFebruary 17

    Recently I've been given an interview where many question were ask, but there was one question I could not answer which was the following: Printing a multi dimensional array using one foreach loop only. $cars = array ( array("Volvo",22,18), arra

  • PyQgis: Print Composer using input from several Spatialite-tables

    PyQgis: Print Composer using input from several Spatialite-tablesNovember 5

    How can I create PDFs out of QGIS using the Print Composer Templates that include a lot of text (from a text-template) and within the text several information comes out of my spatiallite-database. A map is also part of it, but I am only having proble

  • How to Read XML input data from CSV file and print the XML Input data in Email SubjectFebruary 5

    Am from testing background and trying to do Automation using Java. Scenario: I need to Read some data from .csv file and print the data in Email Subject. My Input Sheet is like below To,Subject,EmailBody [email protected],Test,"<?xml version=1.0 encodi

  • Printing verbatim command inputs in commandsMarch 26

    I want to define a command \mydef that does something like this: \mydef{\foo{bar}} produces \def\foo{bar} \verb|\foo=bar| The command: \newcommand{\mydef}[1]{\def #1} does the first bit, but I don't seem to be able to use verbatim in a command - how

  • specify non-printing keys as input to shell command

    specify non-printing keys as input to shell commandJuly 29

    Ubuntu 12.04 LTS Server 64 I have a shell script that runs in unattended mode. The script executes a command that displays a curses/ncurses UI which normally expects the user to navigate a menu via keyboard. To emulate user-navigation, I need to inpu

  • How to print to standard input from WordPress custom plugin PHP code?January 16

    I am developing WordPress theme with lot of custom code. I am having hard time debugging as I don't know how to print/log messages in order to see them on the standard output i.e. terminal. WordPress engine is running on OpenShift platform where I co

  • Why my program prints out the input wrongly?February 3

    I am writing a program in C++ in which I read the data from a text file and print it, then I will sort them after printing. the text file has about 220 lines, which is printing fine except the last 20 lines. I should get this: bsort 2015 penalties de

  • How do I make a user input array or list in python?

    How do I make a user input array or list in python?October 10

    I don't know which one I need actually because I am relatively new to python. What my goal is to have a stand alone script to run multiple buffers based on user input. For example, I would like to ask the user how many buffers and then ask them what

  • Implement "tac": Print lines from a file in reverseOctober 1

    Between the kitten question and seeing this question at U&L about some sed magic, how about implementing tac? Objective Implement a program that will reverse and print the lines in a file. Input A file, provided as a name or via standard input Output

  • How to print output of bash array on single lineJanuary 15

    My code is arr=($(awk '/"*"/' output.txt)) And output.txt says has following content - user { 'xx123': comment => "John Smith", groups => $groups, id => '1234', This is to search all usernames in my target file.It searches eve

  • How to print content of an array February 17

    This question already has an answer here: What's the simplest way to print a Java array? 16 answers I have an array which is filled with inputs from the user and I need to print it. I tried but I get weird results. First im going to enter how many el

Copyright (C) 2017 ceus-now.com, All Rights Reserved. webmaster#ceus-now.com 14 q. 0.465 s.