Printing an array in Java

Author: Roger Morrison
Date Of Creation: 5 September 2021
Update Date: 1 July 2024
Anonim
Printing Arrays - Java Programming Tutorial #22 (PC / Mac 2015)
Video: Printing Arrays - Java Programming Tutorial #22 (PC / Mac 2015)

Content

If you are working with a matrix of a large amount of data in Java, you may want to print certain elements for easier viewing. There are several ways to print arrays in Java and the examples below will guide you through this process. Assume that the name of the array to be printed is "array" with the elements "Elem".

To step

Method 1 of 3: Using the toString command

  1. Determine the elements in your array. Type String [] array = new String [] {"Elem1", "Elem2", "Elem3"} where "ElemX" are the individual elements in your array.
  2. Use the static method with the standard library: Arrays.toString (array). This will give you a string representation of a dimensional arrays. In other words, because it is one-dimensional, you can present the data in rows or columns. This method returns the data in a row, or string.
  3. Run the program. Different compilers have different ways of accomplishing this task. You may be able to go to "Run" or "Start" via "File". You may also have the option to click the "Run" icon in the main menu. The elements will be printed in a string in the bottom window of Java.

Method 2 of 3: Using the asList command

  1. Determine the elements in your array. Type String [] array = new String [] {"Elem1", "Elem2", "Elem3"} where "ElemX" are the individual elements in the array you want.
  2. Use the static method with the standard library: Arrays.asList () for one-dimensional arrays to print as a list.
  3. Run the program. Different compilers have different ways of accomplishing this task. You may be able to go to "Run" or "Start" via "File". You may also have the option to click the "Run" icon in the main menu. The elements will be printed in a row or column in the bottom window of Java.

Method 3 of 3: Printing multi-dimensional arrays

  1. Identify the elements in the array. For a two-dimensional array, there are both rows and columns to be printed. Type for (i = 0; i rows; i ++) for the rows and for (j = 0; j columns; j ++) for the columns.
  2. Use the static method with a standard library: System.out.print (aryNumbers [i] [j] + ""); followed by System.out.println (""); to print arrays within arrays and multidimensional arrays as a line.
  3. Run the program. Different compilers have different ways of accomplishing this task. You may be able to go to "Run" or "Start" via "File". You may also have the option to click the "Run" icon in the main menu. The elements will be printed in a row or column in the bottom window of Java.